【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);
    }
};
相关推荐
致Great1 小时前
Pi 的上下文压缩,到底是怎么工作的?
算法
watersink2 小时前
机器学习聚类算法
算法·机器学习·聚类
luj_17683 小时前
桥牌思维启示:系统设计的模块化架构
c语言·开发语言·c++·经验分享·算法
饼饼学习空间智能5 小时前
家庭服务机器人训练数据怎么积累?仿真、真实采集与持续学习的技术路线分析
人工智能·算法·机器学习
蛋先生DX6 小时前
你瘦不下来但大模型可以:量化原理了解一下
深度学习·算法·llm
Scabbards_6 小时前
面试Leetcode - Heap 堆
java·leetcode·面试
牛阿大7 小时前
LQR算法
算法
(╹◡╹)8 小时前
18.剪枝
算法·机器学习·剪枝
Fa_Mian_Tuan9 小时前
图论基础|邻接矩阵超详细讲解(含无向/有向/带权图+完整可运行C语言代码)
c语言·数据结构·笔记·算法·图论