这道题,处理起来还有点小麻烦,关键是要next两次。。。稍微思考了一下,也是建一个dummy node,会方便很多。。。
第一次代码,简易程度还可以,还写了很多总结,还是很认真的,哈哈:))
代码如下:
/**
* 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) {
// solution 1... 肯能是10天前完成了。。。刚刚一眼看到题目好像做过,然后一想,嗯,好像特别简单。。。几行代码就可以搞定,然后看到自己写了这么多。。。所以来尝试写间接一点,顺便看是不是一遍bug-free,data:1.15.17 for solution2
/* if(head==null || head.next==null) return head;
ListNode tail = new ListNode(0);
tail.next=head;
// in the first switch between first two node, since involves head, so need to op seperately
ListNode x, y;
if(tail.next!=null&& tail.next.next!=null){
x=tail.next;
y=x.next;
x.next=y.next;
tail.next=y;
y.next=x;
head=y; // this is the additional step for head, comparing to the while loop below;
tail=tail.next.next;
}
ListNode a, b;
while(tail.next!=null&& tail.next.next!=null){
a=tail.next;
b=a.next;
a.next=b.next;
tail.next=b;
b.next=a;
tail=tail.next.next;
}
return head;*/
// solution 2 ...... nice, 一遍bug-free,LoC减少了,思路是一样的,但是代码精简了不少。。。命名也规范多了。。。
if(head==null) return null;
ListNode curr=head;
// 头两个节点要特殊处理。。。
if(head.next!=null){
ListNode second=head.next;
curr.next=second.next;
second.next=curr;
head=second;
}
while(curr.next!=null && curr.next.next!=null){
ListNode first=curr.next;
ListNode second=curr.next.next;
first.next=second.next;
second.next=first;
curr.next=second;
curr=first;
}
return head;
}
}
/** solution 1
finish in 15 mins, draw first to figure out the stradegy; make sure two nodes available using anchor.next!null && anchor.next.next!=null
then assign a, b to them, and switch them.
*/
今天的代码,还是有点代码量,但是每句都很短,主要用在最后退出while情况的判断了,有可能剩下2个node,也可能3个。。整个思路还是很流畅,性能也在89%
/**
* 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 dummy = new ListNode(0);
ListNode curr=dummy;
ListNode first=head;
ListNode second=head.next;
while(second.next!=null && second.next.next!=null){
curr.next=second;
curr=curr.next;
second=second.next;
curr.next=first;
curr=curr.next;
first=second;
second=second.next;
}
// 注意!在while结束后,还剩下了2个或者3个node没有处理!!因为你while的条件是那么设置的!!
if(second.next==null){
curr.next=second;
curr=curr.next;
curr.next=first;
first.next=null;
return dummy.next;
}
else{
curr.next=second;
curr=curr.next;
second=second.next;
curr.next=first;
curr=curr.next;
curr.next=second;
return dummy.next;
}
}
}