【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);
    }
};
相关推荐
Greedy Alg5 分钟前
LeetCode 84. 柱状图中最大的矩形(困难)
算法
im_AMBER11 分钟前
Leetcode 52
笔记·学习·算法·leetcode
小欣加油12 分钟前
leetcode 946 验证栈序列
c++·算法·leetcode·职场和发展
包饭厅咸鱼39 分钟前
PaddleOCR----制作数据集,模型训练,验证 QT部署(未完成)
算法
无敌最俊朗@1 小时前
C++ 并发与同步速查笔记(整理版)
开发语言·c++·算法
王哈哈^_^1 小时前
【完整源码+数据集】课堂行为数据集,yolo课堂行为检测数据集 2090 张,学生课堂行为识别数据集,目标检测课堂行为识别系统实战教程
人工智能·算法·yolo·目标检测·计算机视觉·视觉检测·毕业设计
夏鹏今天学习了吗1 小时前
【LeetCode热题100(66/100)】寻找两个正序数组的中位数
算法·leetcode·职场和发展
墨染点香1 小时前
LeetCode 刷题【151. 反转字符串中的单词】
算法·leetcode·职场和发展
ytttr8732 小时前
Landweber迭代算法用于一维、二维图像重建
人工智能·算法·机器学习