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
相关推荐
Tisfy3 小时前
LeetCode 3516.找到最近的人:计算绝对值大小
数学·算法·leetcode·题解
黑色的山岗在沉睡3 小时前
LeetCode 189. 轮转数组
java·算法·leetcode
墨染点香3 小时前
LeetCode 刷题【65. 有效数字】
算法·leetcode·职场和发展
Tisfy4 小时前
LeetCode 3027.人员站位的方案数 II:简单一个排序O(n^2)——ASCII图解
leetcode·题解·思维·排序·hard
源代码•宸4 小时前
Leetcode—2749. 得到整数零需要执行的最少操作数【中等】(__builtin_popcountl)
c++·经验分享·算法·leetcode·位运算
用户4822137167754 小时前
深度学习——AlexNet网络结构
算法
豆沙沙包?4 小时前
2025年- H118-Lc86. 分隔链表(链表)--Java版
java·数据结构·链表
张子夜 iiii5 小时前
传统神经网络实现-----手写数字识别(MNIST)项目
人工智能·pytorch·python·深度学习·算法