【leetcode】反转链表-25-2

方法:遍历

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) {
        ListNode* A=nullptr;
        ListNode* B=nullptr;
        while(head!=nullptr){
            B=head;
            head=head->next;
            B->next=A;
            A=B;
        }
        head=B;
        return head;

    }
};

方法:递归

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* recurveReverseList(ListNode* A,ListNode* B){
        if(B->next==nullptr){
            B->next=A;
            return B;
        }
        ListNode* T=B;
        B=B->next;
        T->next=A;
        A=T;
        return recurveReverseList(A,B);
    }
    ListNode* reverseList(ListNode* head) {
        if(head==nullptr){
            return head;
        }
        return recurveReverseList(nullptr,head);
    }
};
相关推荐
INGNIGHT8 分钟前
815 · 课程表IV(dfs)
算法·深度优先
文丑颜不良啊30 分钟前
LeetCode1~50题目解析
leetcode
Pniubi37 分钟前
力扣146.LRU缓存机制
算法·leetcode·缓存
云上工程笔记40 分钟前
2026年7B到67B模型训练与推理GPU配置评测:LoRA、量化与全量微调对比
人工智能·算法·机器学习
softlgh41 分钟前
鼾声识别:嵌入式离线鼾声检测 SDK 与睡眠健康数据
算法·智能家居·智能音箱·鼾声识别·智能枕头·打呼噜
了了1 小时前
图搜索基础学习笔记
算法
淡海水1 小时前
05-02-源码-Boehm GC标记阶段
算法·unity·c#·游戏引擎·gc
Code_Solitude2 小时前
传智杯备赛代码整理(前4题)
数据结构·算法
Jasmine_llq2 小时前
《P8816 [CSP-J 2022] 上升点列》
数据结构·算法·贪心·排序·二维动态规划 dp·类背包状态转移
hetao17338372 小时前
2026-10-19 hetao1733837 的刷题记录
c++·算法