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
相关推荐
嘴贱欠吻!4 小时前
Flutter鸿蒙开发指南(七):轮播图搜索框和导航栏
算法·flutter·图搜索算法
张祥6422889044 小时前
误差理论与测量平差基础笔记十
笔记·算法·机器学习
踩坑记录4 小时前
leetcode hot100 2.两数相加 链表 medium
leetcode·链表
qq_192779875 小时前
C++模块化编程指南
开发语言·c++·算法
cici158746 小时前
大规模MIMO系统中Alamouti预编码的QPSK复用性能MATLAB仿真
算法·matlab·预编码算法
历程里程碑6 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
2501_940315268 小时前
航电oj:首字母变大写
开发语言·c++·算法
CodeByV8 小时前
【算法题】多源BFS
算法
TracyCoder1238 小时前
LeetCode Hot100(18/100)——160. 相交链表
算法·leetcode
浒畔居8 小时前
泛型编程与STL设计思想
开发语言·c++·算法