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
相关推荐
John_Rey8 小时前
API 设计哲学:构建健壮、易用且符合惯用语的 Rust 库
网络·算法·rust
愿没error的x8 小时前
动态规划、贪心算法与分治算法:深入解析与比较
算法·贪心算法·动态规划
NONE-C8 小时前
动手学强化学习 第6章 Dyna-Q 算法
算法
惊讶的猫8 小时前
面向无监督行人重识别的摄像头偏差消除学习
人工智能·算法·机器学习
深度学习机器8 小时前
RAG Chunking 2.0:提升文档分块效果的一些经验
人工智能·算法·llm
努力学习的小全全9 小时前
【CCF-CSP】05-01数列分段
数据结构·算法·ccf-csp
遗憾是什么.9 小时前
数据结构 -- 栈
数据结构·算法·链表
清风er9 小时前
智能座舱开发
算法·计算机视觉
Learn Beyond Limits10 小时前
Data Mining Tasks|数据挖掘任务
人工智能·python·神经网络·算法·机器学习·ai·数据挖掘
Croa-vo10 小时前
Citadel SDE 面试复盘:直面硬核算法与思维挑战的双重压力
算法·面试·职场和发展