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.
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.
AC代码:
public class Solution {
public ListNode swapPairs(ListNode head) {
if( head == null || head.next == null )
return head;
ListNode dummyHead = new ListNode(-1);
ListNode dummyCurr = dummyHead;
ListNode p = head;
ListNode q = p.next;
ListNode temp;
while( p.next != null ){
temp = q.next;
q.next = null;
dummyCurr.next = q;
dummyCurr = dummyCurr.next;
dummyCurr.next = p;
dummyCurr = dummyCurr.next;
p.next = null;
p = temp;
if( p == null ) break;
q = p.next;
}
if( p != null ) dummyCurr.next = p;
return dummyHead.next;
}
}