【算法拾光】递归|反转链表 两两交换链表中的结点

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

第一题:反转链表(LeetCode 206)

题目分析

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

算法原理

  1. 递归终止:head == nullptr 或者 head->next == nullptr,直接返回(空 / 最后一个节点,就是新头)
  2. 递归调用 reverseList(head->next),拿到子链表反转后的头 newHead
  3. head->next->next = head:后一个节点反过来指向当前节点
  4. head->next = nullptr:断开原来的正向边,防止环
  5. 返回 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。

算法原理

  1. 终止条件:head == nullptr 或者只有一个节点,直接返回
  2. 设 first = head,second = head->next
  3. 递归处理后面一组:second->next = swapPairs(second->next)
  4. 交换:second->next = first
  5. 返回 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;
    }
};

总结

递归链表题套路:

  • 先交给递归搞定后面部分;
  • 再调整当前节点和下一个节点之间的指针;
  • 想好什么时候停止递归(边界)。
相关推荐
金榜题名萱1 小时前
蓝桥杯 - 旗帜
c语言·数据结构·c++·算法·蓝桥杯
我是伪码农3 小时前
12.5程序设计
数据结构·算法
Shaoshing3 小时前
LeetCode100 152.乘积最大子数组
数据结构·算法·leetcode
凡人叶枫3 小时前
数据结构分类与基本类型:线性、非线性、连续与分散
数据结构·c++
风落青芜3 小时前
C++模板初阶:函数模板与类模板
开发语言·数据结构·c++·算法
郝学胜-神的一滴14 小时前
游戏设计、原型与开发 26:四种循环
开发语言·数据结构·游戏·游戏引擎·游戏策划
Thanks_ks15 小时前
Python 列表与元组:可变性与不可变性的差异及使用场景选择
数据结构·python·列表·元组·可变对象·不可变对象·可哈希
@三十一Y1 天前
C++高阶数据结构:图
开发语言·数据结构·c++
夏日听雨眠1 天前
数据结构( Floyd)
数据结构·算法