Well, since the head
pointer may also been modified, we create a then points to it facilitate the swapping new_head
Proce Ss.
For the example list 1 -> 2 -> 3 -> 4
in the problem statement, it'll become 0 -> 1 -> 2 -> 3 -> 4
(we init to be new_head -> val
0
). We set a pointer to pre
and new_head
another to cur
head
. Each time, we'll swap pre -> next
and cur -> next
using the following piece of code.
Pre-, next = cur, next = Next, next--next = cur;
After swapping them, we update as follows:
Pre =
To swap the next and the nodes.
Finally, we return new_head -> next
.
The complete code is as follows.
1 classSolution {2 Public:3listnode* Swappairs (listnode*head) { 4 if(!head | |! (Head-to-next))returnhead;5listnode* New_head =NewListNode (0);6New_head-Next =head;7listnode* pre =New_head;8listnode* cur =head;9 while(Pre, next && curnext) {TenPre, next = curNext; OneCur next = cur, nextNext; APre-Next Next =cur; -Pre =cur; -Cur = PreNext; the } - returnNew_headNext; - } -};
[Leetcode] Swap Nodes in Pairs