Problem
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:
1 | |
Explanation
-
From the problem example, we need to swap $1$ and $2$, then swap $3$ and $4$. In order to swap $3$ and $4$, we need a pointer that can point both node. In this case, to swap $3$ and $4$, we need a pre-node pointing at $2$, this pre-node can represent $3$ using
pre.nextand represent $4$ usingpre.next.next. So, in order to swap the first two elements, we need to create a dummy node in front of the input’s head. -
Now, the node become this:
pre->1->2->3->4. The solution basically do:1
2
3pre->2->3->4 1->3->4 pre->2->1->3->4 -
After we swap, we move the
prepointing topre.next.nextand repeat the above process.
Solution
1 | |