思路:递归思想
2->1->4->3->5 链表,head=21互换,变12的返回值,其中2的next等于调用下一层435的返回值,43互换变34返回值节点3给2的next,4的next调用递归5的返回值
# include<iostream> # include<vector> # include<string> # include<algorithm> # include<math.h> # include<climits> # include<stack> # include<queue> using namespace std; struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; ListNode* swaptwo(ListNode* head) { if (!head)return head;//head空返回NULL if (!head->next) return head;//只有一个head无下一个节点直接返回 ListNode* p = head->next; head->next = swaptwo(p->next);//递归下一部分的链表 p->next = head; return p;//返回新头 } ListNode* swapPairs(ListNode* head) { head = swaptwo(head); return head; } int main(void) { ListNode* head = new ListNode(2, new ListNode(1, new ListNode(4, new ListNode(3, new ListNode(5)))));// 2->1->4->3->5 链表 head = swapPairs(head); ListNode* p = head; while (p) { cout << p->val << " "; p = p->next; }//输出应该是 1->2->3->4->5 cout << endl; system("pause"); return 0; }