Topic
Given a linked list, swap every, adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. Modify the values in the list, only nodes itself can be changed.
Analysis
Using recursive resolution, the first step out of the recursive condition must be the remaining length of the list is 0 or 1, that is, head = = Null,head->next = NULL. Second, be sure to pay attention to the list of remaining nodes in the case of reversing two nodes, otherwise, head->next are empty, how to reverse the back node? See the note below for details.
Code
Run Time 4ms
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: listnode* swappairs (listnode* head) { if (head = = NULL | | head->next = = NULL) //recursive bounce condition ret URN Head; listnode* tmp = Swappairs (head->next->next); Must be in front recursion, if the head->next are empty, recursive into can be seen, but the following directly to Head->next will not be judged. listnode* res = head->next; Res->next = head; Res->next->next = tmp; return res; }};
Swap Nodes in pairs--problem solving report