【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);
    }
};
相关推荐
donoot1 小时前
PaddleOCR + PyMuPDF 生成【全兼容双层 PDF】完整实操指南
人工智能·算法·pymupdf·paddleocr·双层pdf
paeamecium2 小时前
【PAT甲级真题】- Rational Sum (20)
数据结构·c++·python·算法·pat考试·pat
拳里剑气11 小时前
C++算法:BFS解决FloodFill算法
c++·算法·bfs·宽度优先
wanderist.13 小时前
Lambda表达式在算法竞赛中的应用
java·开发语言·算法
稚南城才子,乌衣巷风流13 小时前
支配树(Dominator Tree)详解:概念、算法与应用
算法
稚南城才子,乌衣巷风流14 小时前
动态开点:原理、实现与应用场景
数据结构·算法
yyds_yyd_1008614 小时前
1464. 数组中两元素的最大乘积(2026.07.27)
数据结构·c++·算法·leetcode
KaMeidebaby15 小时前
卡梅德生物技术快报 | 核酸适配体文库测序:核酸适配体文库测序的技术原理、实验流程与数据解析
前端·网络·数据库·人工智能·算法
geovindu15 小时前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法