【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);
    }
};
相关推荐
长安er6 小时前
LeetCode215/347/295 堆相关理论与题目
java·数据结构·算法·leetcode·
元亓亓亓6 小时前
LeetCode热题100--62. 不同路径--中等
算法·leetcode·职场和发展
小白菜又菜6 小时前
Leetcode 1925. Count Square Sum Triples
算法·leetcode
登山人在路上7 小时前
Nginx三种会话保持算法对比
算法·哈希算法·散列表
写代码的小球8 小时前
C++计算器(学生版)
c++·算法
AI科技星8 小时前
张祥前统一场论宇宙大统一方程的求导验证
服务器·人工智能·科技·线性代数·算法·生活
Fuly10249 小时前
大模型剪枝(Pruning)技术简介
算法·机器学习·剪枝
Xの哲學9 小时前
Linux网卡注册流程深度解析: 从硬件探测到网络栈
linux·服务器·网络·算法·边缘计算
bubiyoushang8889 小时前
二维地质模型的表面重力值和重力异常计算
算法
仙俊红9 小时前
LeetCode322零钱兑换
算法