24. Swap Nodes in Pairs

Iterative Pairwise Swap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode current = dummy;

while(current.next != null && current.next.next != null) {
ListNode first = current.next;
ListNode second = current.next.next;

first.next = second.next;
second.next = first;
current.next = second;

current = first;
}

return dummy.next;
}
}

Remarks:

  1. TC: $O(n)$, SC: $O(1)$
  2. Be careful of processing node swaps