
递归解链表题核心思路:先处理后面的子链表,再回头调整当前节点的指针,不要一上来就想循环。
第一题:反转链表(LeetCode 206)
题目分析

给单链表头结点,返回反转后的新头。 递归思路:把 head->next 开始的子链表先反转好,再让后面节点指向自己,自己指向 nullptr。
算法原理

- 递归终止:
head == nullptr或者head->next == nullptr,直接返回(空 / 最后一个节点,就是新头) - 递归调用
reverseList(head->next),拿到子链表反转后的头newHead head->next->next = head:后一个节点反过来指向当前节点head->next = nullptr:断开原来的正向边,防止环- 返回
newHead
C++ 代码
cpp
#include <iostream>
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) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}
};
第二题:两两交换链表中的结点(LeetCode 24)
题目分析


给链表,两两交换相邻节点,不能直接改值,只能改指针。例:1->2->3->4 → 2->1->4->3。
算法原理

- 终止条件:
head == nullptr或者只有一个节点,直接返回 - 设
first = head,second = head->next - 递归处理后面一组:
second->next = swapPairs(second->next) - 交换:
second->next = first - 返回
second(这一组新的头)
C++ 代码
cpp
#include <iostream>
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) {}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* first = head;
ListNode* second = head->next;
// 递归处理后面的链表
first->next = swapPairs(second->next);
second->next = first;
return second;
}
};
总结
递归链表题套路:
- 先交给递归搞定后面部分;
- 再调整当前节点和下一个节点之间的指针;
- 想好什么时候停止递归(边界)。
