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
相关推荐
Chat_zhanggong34517 分钟前
主推NT98336BG作用有哪些?
嵌入式硬件·算法
Run_Teenage36 分钟前
算法:线段树
算法
Westward-sun.38 分钟前
YOLOv2算法全方位解析:从BatchNorm到聚类先验框的九大改进
算法·yolo·聚类
扶苏xw40 分钟前
【离散化算法】
算法
码之气三段.41 分钟前
Codeforces Round 1095 (Div. 2) 补题
算法
6Hzlia41 分钟前
【Hot 100 刷题计划】 LeetCode 189. 轮转数组 | C++ 三次反转经典魔法 (O(1) 空间)
c++·算法·leetcode
wuweijianlove43 分钟前
算法可扩展性建模与渐进性能分析的技术7
算法
shehuiyuelaiyuehao1 小时前
算法14,滑动窗口,找到字符串中所有字母异位词
算法
凯瑟琳.奥古斯特1 小时前
图论核心考点精讲
开发语言·数据结构·算法·排序算法·哈希算法
WolfGang0073211 小时前
代码随想录算法训练营 Day49 | 图论 part07
算法·图论