24. Swap Nodes in Pairs
Last updated
Was this helpful?
Last updated
Was this helpful?
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Thoughts:
Recusively solve the problem, but O(n) extra space
Iteratively: Here,pre
is the previous node. Since the head doesn't have a previous node, I just useself
instead. Again,a
is the current node andb
is the next node. To go frompre -> a -> b -> b.next
topre -> b -> a -> b.next
, we need to change those three references. Instead of thinking about in what order I change them, I just change all three at once.('s )
Code: Recursively swaping every pairs
Code: Iteratively
Code: Iteratively