/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head){
if(!head || !head -> next)
return head;
struct ListNode *newHead = head -> next;
head -> next = swapPairs(newHead -> next);
newHead -> next = head;
return newHead;
}
Given that a linked list, 1 -> 2 -> 3 -> 4 -> 5, I know that when this linked list enter the function signature, "struct ListNode* swapPairs(struct ListNode* head)", "*newHead" is the node containing value 2, which is the second node of the linked list.
head is the pointer to the first node containing value 1. newHead -> next is the pointer to the node containing value 3 (3rd node).
But why "head -> next = swapPairs(newHead -> next)" returns the node containing value 3, which is the third node of the linked list? I don't get why "swapPairs(newHead -> next)" can make "head -> next" point to the third node of the linked list.
I expected that "swapPairs(newHead -> next)" will return a linked list pointer, with a linked list 4 -> 3 -> 5" to "head -> next".
I thought it will return the node containing value 4 and all the pair nodes are swapped after the second node of the linked list.