[leetcode] problem 24 – swap nodes in pairs

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list, only nodes itself can be changed.

Example

Given 1->2->3->4, you should return the list as 2->1->4->3.

Code

1
2
3
4
5
public class  {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public ListNode swapPairs(ListNode head) {
ListNode node = new ListNode(0);
node.next = head;
ListNode prev = node;

while (prev.next != null && prev.next.next != null) {
ListNode current = prev.next;
ListNode next = prev.next.next;
current.next = next.next;
next.next = current;
prev.next = next;
prev = current;
}

return node.next;
}