Swap Nodes in Pairs LeetCode 解题报告
2017-08-17 00:23
429 查看
题目
Given a linked list, swap every two adjacent nodes and return its head.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.
思路
考单链表的题目,交换每相邻两个元素的顺序,这里我们可以通过创建一个头指针(空元素)指向第一个元素。过程如下:1、创建一个空元素dummy,指向单链表首元素head,并把其设为当前元素cur
2、创建两个指针first和second分别指向当前元素的下一个元素和下下个元素。
3、将first指向second的下一个,second指向first,当前元素cur指向cur的下下个元素
4、返回元素的首元素(空元素的下一个)
代码
public ListNode swapPairs(ListNode head) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode cur = dummy; while(cur.next != null && cur.next.next != null){ ListNode first = cur.next; ListNode second = cur.next.next; first.next = second.next; second.next = first; cur.next = second; cur = cur.next.next; } return dummy.next; }
相关文章推荐
- LeetCode 24. Swap Nodes in Pairs 解题报告
- LeetCode解题报告--Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs 解题报告
- leetcode解题报告24. Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs 解题报告
- 【LeetCode】Swap Nodes in Pairs 解题报告
- [leetcode] 24. Swap Nodes in Pairs 解题报告
- [Leetcode] 24. Swap Nodes in Pairs 解题报告
- LeetCode: Swap Nodes in Pairs 解题报告
- 【LeetCode】Swap Nodes in Pairs 解题报告
- LeetCode解题报告—— Swap Nodes in Pairs & Divide Two Integers & Next Permutation
- [LeetCode] Swap Nodes in Pairs 解题报告
- leetcode解题方案--024--Swap Nodes in Pairs
- leetCode 24. Swap Nodes in Pairs (双数交换节点) 解题思路和方法
- Swap Nodes in Pairs ——解题报告
- [leetcode javascript解题]Swap Nodes in Pairs
- leetCode 24. Swap Nodes in Pairs (双数交换节点) 解题思路和方法
- Leetcode:Swap Nodes in Pairs 单链表相邻两节点逆置
- LeetCode - 24 - Swap Nodes in Pairs(交换链表结点)
- Leetcode: 24. Swap Nodes in Pairs