Leetcode 206. 反转链表 迭代/递归

原题链接:Leetcode 206. 反转链表

解法一:迭代

cpp 复制代码
/**
 * Definition for singly-linked list.
 * 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) return nullptr;
        ListNode* pre = nullptr;
        ListNode* now = head;
        while(now){
            ListNode* next = now->next;
            now->next = pre;
            pre = now;
            now = next;
        }
        return pre;
    }
};

解法二:递归

cpp 复制代码
/**
 * Definition for singly-linked list.
 * 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;
    }
};
// 链表:1 -> 2 -> 3 -> 4 -> 5
// 递归调用顺序:
// reverseList(1)
//     reverseList(2)
//         reverseList(3)
//             reverseList(4)
//                 reverseList(5)
// 5->next==nullptr,返回 5
// newhead=5,head=4, 4->next=5, 5->next = 4(反转),4->next=nullptr
// newhead=5,head=3, 3->next=4, 4->next = 3(反转),3->next=nullptr
// newhead=5,head=2, 2->next=3, 3->next = 2(反转),2->next=nullptr
// newhead=5,head=1, 1->next=2, 2->next = 1(反转),1->next=nullptr
// return  newhead=5
相关推荐
洋不写bug2 分钟前
链表补充练习,双链表的模拟实现
java·数据结构·链表·双链表·底层实现
residual_fan4 分钟前
持续对比强化学习(Continual Contrastive Reinforcement Learning)论文分享
人工智能·算法·数据挖掘·数据分析
s_w.h20 分钟前
【 计网 】序列化与反序列化
linux·服务器·网络·算法·bash
信奥卷王41 分钟前
2025年09月GESPC++五级真题解析(含视频)
算法
白狐_79841 分钟前
408 数据结构|外部排序:流程与 k 路归并
数据结构·算法
闻缺陷则喜何志丹1 小时前
【动态规划】P3609 [USACO17JAN] Hoof, Paper, Scissor G
c++·算法·动态规划·洛谷
heima20161 小时前
长期复盘:拼团活动链接开发公司的行业现状与困境洞察
链表
leihefeng1 小时前
手写数字识别:KNN vs 逻辑回归实战
python·算法·机器学习·逻辑回归·scikit-learn
全栈技术负责人2 小时前
DeepSeek Harness 业务工具权限插件 dsh-tool-permission设计思路
网络·算法·ai·ai编程
mmmmath_32 小时前
面试题 02.07. 链表相交
算法·链表