leetcode 92. Reverse Linked List II

题目描述

92. Reverse Linked List II 是第206题的进阶版206. Reverse Linked List

思路很简单,但一次性通过还是有点难度的。

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* reverseBetween(ListNode* head, int left, int right) {
        if(left == right)
            return head;
        ListNode* firstTail = nullptr;
        ListNode* leftHead = head;
        for(int i = 1;i < left;i++){
            firstTail = leftHead;
            leftHead = leftHead->next;
        }

        int count = right - left;
        ListNode* pre = leftHead;
        ListNode* cur = leftHead->next;
        ListNode* temp = nullptr;
        while(count--){
            temp = cur->next;
            cur->next=pre;
            pre = cur;
            cur = temp;
        }
        
        leftHead->next = temp;    
        if(head == leftHead){
            head = pre;
        }else{
            firstTail->next = pre;
        }
        return head;
    }
};

对比leetcode 206. 反转链表-CSDN博客

相关推荐
蛋蛋的就会顺顺的9 小时前
hot100 p0——栈,贪心算法,动态规划
java·前端·javascript·算法·leetcode·力扣
Navigator_Z11 小时前
LeetCode //C - 1291. Sequential Digits
c语言·算法·leetcode
longlongzihan15 小时前
C++ 常用数据结构速查:vector、stack、queue、list、树、图、哈希表等声明与核心操作
数据结构·c++·list
0+11116 小时前
算法 --栈
算法·leetcode
圣保罗的大教堂16 小时前
leetcode 3723. 数位平方和的最大值 中等
leetcode
浅念-18 小时前
动态规划:线性DP——多状态DP与子数组专题笔记
c++·笔记·算法·leetcode·职场和发展·动态规划·力扣
学电子她就能回来吗19 小时前
LeetCode Hot 100|滑动窗口专题零基础学习笔记
笔记·学习·leetcode
拾饵94220 小时前
面试回答整理(Q1–Q3)
leetcode
虚无的纽扣20 小时前
【力扣刷题】第四天:三数之和、四数之和
算法·leetcode·职场和发展
_不会dp不改名_21 小时前
leetcode_3273 数位平方和的最大值
算法·leetcode·职场和发展