问题描述:
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.
原问题链接:https://leetcode.com/problems/swap-nodes-in-pairs/
问题分析
这个问题看起来比较简单,主要是要对里面的实现细节考虑清楚了。我们可以结合一个图来考虑。
假定我们有这么一个链表,我们首先设定它们要交换的两个元素分别为first, second。
因为要交换first, second, 所以首先将first.next赋值给second.next:
然后再将first.next指向second:
由上图很明显,我们还需要调整pre引用,使得pre.next = first:
上面的描述是针对某个时候节点调整的细节。不过既然前面要求是对整个链表里每两个相邻的元素都这么调整。那么这里必然是用一个循环来处理。在每个循环的开始,我们将pre.next赋值给second,pre.next.next赋值给first。因为链表里元素可能有奇数个或者偶数个元素,我们可以将pre.next != null && pre.next.next != null作为循环跳出的条件。
这样,作为一个完整的循环。我们会在每个循环的开始将pre.next, pre.next.next分别赋值给second和first。同时在调整结束后将pre设置为second的值。这样方便在下一个循环继续调整。
按照前面的讨论,详细实现的代码如下:
/**
* 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) {
if(head == null || head.next == null) return head;
ListNode temp = new ListNode(0);
temp.next = head;
ListNode pre = temp, first = null, second = null;
while(pre.next != null && pre.next.next != null) {
first = pre.next.next;
second = pre.next;
second.next = first.next;
first.next = second;
pre.next = first;
pre = second;
}
return temp.next;
}
}