Swap Nodes in Pairs

Swap Nodes in Pairs

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.

Solution In-Place

  • Use a dummyhead to avoid dealin with null cases, as usual
  • Keep track of the first node in next pair
  • Termination conditions: take care of odd and even node number cases
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static ListNode swapPairs(ListNode head) {
ListNode dummyhead = new ListNode(0);
dummyhead.next = head; //use dummyhead to deal with null case
ListNode first = dummyhead;
ListNode second =head;
while(second!=null && second.next!=null){//when second is null (odd), or second next is null(even)
ListNode tmp = second.next.next; //record next start
second.next.next = second; //reverse
first.next = second.next; // link to second
second.next = tmp; // link to next start
first=second; // move to next
second = second.next; //move to next
}
return dummyhead.next;
}