List · leetcode-24. 交换相邻节点
题面
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
给定链表,交换相邻的两个节点,并非返回头节点。
样例
Given1->2->3->4
, you should return the list as2->1->4->3
.
思路
来自于不知名大佬,递归解决。
head->next = swapPairs(head->next->next);
从链表末尾开始交换。(从前往后交换头节点就会丢失)
样例推导过程(结合code来看)
源码(仅仅十来行,🐮)
1 class Solution { 2 public: 3 ListNode* swapPairs(ListNode* head) { 4 if(head == nullptr || head->next == nullptr) 5 return head; 6 7 ListNode* res = head->next; 8 head->next = swapPairs(head->next->next); 9 res->next = head; 10 11 return res; 12 } 13 };