24. Swap Nodes in Pairs

Recursion

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}

// nodeA -> nodeB -> ...
ListNode nodeA = head, nodeB = head.next;
ListNode nextHead = nodeB.next;

nodeB.next = nodeA;
nodeA.next = swapPairs(nextHead);
return nodeB;
}
}

Iterate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummyHead = new ListNode(-1, head);
ListNode pre = dummyHead;

ListNode curr = head;
while (curr != null && curr.next != null) {
ListNode nodeA = curr, nodeB = curr.next;
ListNode nextCurr = nodeB.next;

nodeB.next = nodeA;
nodeA.next = nextCurr;

pre.next = nodeB;

curr = nextCurr;
pre = nodeA;
}

return dummyHead.next;
}
}

References

24. Swap Nodes in Pairs