题注
这道题吧,看起来挺简单的,但是里面涉及到一些细节问题,很容易就错了,在实现之前最好仔细考虑一下各个细节。
问题
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.
分析
首先,题目要求使用固定的存储空间。也就是说,不允许根据以前的List,构造一个新的List,只能在原List中操作。不过我做的时候,看成了不能使用任何额外的存储空间(引用传递除外),因此我做的时候挑战稍微更多一些。
我们要仔细考虑的问题是,对于一个swap,到底应该修改几个引用传递呢?我们以1->2->3->4->5来举例:
对于1->2->3这个List好理解,一共修改两个:2->1,1->3即可。
第一个Swap转换完毕后,对于2->1->3->4->5这个List,一共需要修改三个:4->3,3->5,还有一个非常容易忽略的就是1->4。忽略的原因就是1->2->3这个List中,2最后变成了head,不需要进行第三个修改了。这点需要特别注意。其他的就没什么了。
代码
正要提交代码呢,结果优快云似乎有点抽了,不让我提交啊… 那就干脆粘贴在这里吧。
public class Solution {
public ListNode swapPairs(ListNode head) {
ListNode rootNode = head;
ListNode accessNode = head;
if (head == null){
return null;
}
if (head.next == null){
return head;
}
//Deal with Node 1 and Node 2
accessNode = accessNode.next;
rootNode = accessNode;
ListNode nextNode = accessNode.next;
accessNode.next =head;
accessNode = head;
accessNode.next = nextNode;
//Deal with other Nodes
while(accessNode.next != null && accessNode.next.next != null){
ListNode node1 = accessNode.next;
ListNode node2 = accessNode.next.next;
ListNode node3 = accessNode.next.next.next;
node2.next = node1;
node1.next = node3;
accessNode.next = node2;
accessNode = accessNode.next.next;
}
return rootNode;
}
}