【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);
    }
};
相关推荐
夏末秋也凉26 分钟前
力扣-回溯-491 非递减子序列
数据结构·算法·leetcode
penguin_bark28 分钟前
三、动规_子数组系列
算法·leetcode
kyle~37 分钟前
thread---基本使用和常见错误
开发语言·c++·算法
曲奇是块小饼干_1 小时前
leetcode刷题记录(一百零八)——322. 零钱兑换
java·算法·leetcode·职场和发展
小wanga1 小时前
【leetcode】滑动窗口
算法·leetcode·职场和发展
少年芒1 小时前
Leetcode 490 迷宫
android·算法·leetcode
BingLin-Liu2 小时前
蓝桥杯备考:搜索算法之枚举子集
算法·蓝桥杯·深度优先
码农诗人2 小时前
调用openssl实现加解密算法
算法·openssl·ecdh算法
IT猿手2 小时前
2025最新智能优化算法:鲸鱼迁徙算法(Whale Migration Algorithm,WMA)求解23个经典函数测试集,MATLAB
android·数据库·人工智能·算法·机器学习·matlab·无人机
别NULL2 小时前
机试题——编辑器
c++·算法