LeetCode : Swap Nodes in Pairs [java]
2016-03-08 00:43
531 查看
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
思路:纯链表操作,使用额外节点记录"指针",主要需要记录的是:当前交换的两个节点,两个节点后的节点(如果有的话)以及构建新链表的"指针".
For example,
Given
1->2->3->4, you should return the list as
2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
思路:纯链表操作,使用额外节点记录"指针",主要需要记录的是:当前交换的两个节点,两个节点后的节点(如果有的话)以及构建新链表的"指针".
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode swapPairs(ListNode head) { ListNode myHead = new ListNode(-1); ListNode myPointer = myHead; while (head != null) { ListNode next2 = head.next; if (next2 == null) { myPointer.next = head; break; } else { next2 = next2.next; ListNode qian = head; ListNode hou = head.next; qian.next = hou.next; hou.next = qian; myPointer.next = hou; myPointer = myPointer.next.next; head = next2; } } return myHead.next; } }
相关文章推荐
- 三种Node.js写文件的方式
- Node.js笔记之模块机制
- [C语言][LeetCode][19]Remove Nth Node From End of List
- leetcode:Populating Next Right Pointers in Each Node II 【Java】
- 237. Delete Node in a Linked List
- leetcode:Populating Next Right Pointers in Each Node 【Java】
- 237. Delete Node in a Linked List
- 小明去银行取钱了(同步异步、阻塞与非阻塞)
- nodeclub 学习记录
- Adjacent Node Sum (图的邻接表表示 C语言)
- node.js
- LeetCode : Remove Nth Node From End of List [java]
- [nodejs] 格式化日期、ejs模板引擎改变.ejs为.html、mongoose查询所有
- Node.js写文件的三种方法
- node.js文件图片上传
- 利用doker快速搭建node.js运行环境
- Adjacent Node Sum(邻接表处理)
- Hadoop namenode 不能启动解决方案
- 手把手教你做爬虫---基于NodeJs
- Wow6432Node