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.
这题想法和Merge Two Sorted Linked List类似,也是建一个fakeHead,然后一个一个把原来链表里的node插到新链表里。
比如这个1->2,p1=1。那么dummyP.next=2, nextHead=p1.next.next. dummyP.next.next = 1.最后p1.next=null。一定要记住最后一步,要不然新链表就是2121212121....没完没了了
public class Solution {
public ListNode swapPairs(ListNode head) {
ListNode fakeHead = new ListNode(0);
ListNode dummyP = fakeHead;
ListNode p1 = head;
ListNode nextHead;
while(p1 != null){
if(p1.next == null){
dummyP.next = p1;
break;
}
nextHead = p1.next.next;
dummyP.next = p1.next;
p1.next.next = p1;
//must set p1.next = null to avoid self loops
p1.next = null;
p1 = nextHead;
dummyP = dummyP.next.next;
}
return fakeHead.next;
}
}