24. Swap Nodes in Pairs
Asked at 14Bloomberg53Microsoft46Amazon39Google34Meta28josh technology50tcs27Altimetrik69Arista Networks60Uber50PayPal42TikTok41Yandex28Goldman Sachs21
Problem
Swap every two adjacent nodes of a linked list by relinking them (not by changing values), and return the head.
Example: 1→2→3→4 → 2→1→4→3; 1→2→3 → 2→1→3
With prev before each pair a → b: rewire to prev → b → a → (rest) and advance prev = a.
Complexity: O(n).
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = prev = ListNode(0, head)
while prev.next and prev.next.next:
a, b = prev.next, prev.next.next
prev.next, a.next, b.next = b, b.next, a
prev = a
return dummy.next
assert list_vals(Solution().swapPairs(make_list([1, 2, 3, 4]))) == [2, 1, 4, 3]
assert list_vals(Solution().swapPairs(make_list([1, 2, 3]))) == [2, 1, 3]
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0, head), prev = dummy;
while (prev.next != null && prev.next.next != null) {
ListNode a = prev.next, b = a.next;
a.next = b.next;
b.next = a;
prev.next = b;
prev = a;
}
return dummy.next;
}
}
func swapPairs(head *ListNode) *ListNode {
dummy := &ListNode{Next: head}
prev := dummy
for prev.Next != nil && prev.Next.Next != nil {
a, b := prev.Next, prev.Next.Next
prev.Next, a.Next, b.Next = b, b.Next, a
prev = a
}
return dummy.Next
}