Well, since the head
pointer may also been modified, we create a new_head
that points to it to facilitate the swapping process.
For the example list 1 -> 2 -> 3 -> 4
in the problem statement, it will become 0 -> 1 -> 2 -> 3 -> 4
(we init new_head -> val
to be 0
). Then we set a pointer pre
to new_head
and anothercur
to head
. Each time, we will swap pre -> next
and cur -> next
using the following piece of code.
pre -> next = cur -> next; cur -> next = cur -> next -> next; pre -> next -> next = cur;
After swapping them, we update as follows:
pre = cur;
cur = pre -> next;
to swap the next two nodes.
Finally, we return new_head -> next
.
The complete code is as follows.
1 class Solution { 2 public: 3 ListNode* swapPairs(ListNode* head) { 4 if (!head || !(head -> next)) return head; 5 ListNode* new_head = new ListNode(0); 6 new_head -> next = head; 7 ListNode* pre = new_head; 8 ListNode* cur = head; 9 while (pre -> next && cur -> next) { 10 pre -> next = cur -> next; 11 cur -> next = cur -> next -> next; 12 pre -> next -> next = cur; 13 pre = cur; 14 cur = pre -> next; 15 } 16 return new_head -> next; 17 } 18 };