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博客

相关推荐
刃神太酷啦1 天前
聚焦 string:C++ 文本处理的核心利器--《Hello C++ Wrold!》(10)--(C/C++)
java·c语言·c++·qt·算法·leetcode·github
哎写bug的程序员2 天前
leetcode复盘(1)
算法·leetcode·职场和发展
qq_534452522 天前
【算法 day02】LeetCode 209.长度最小的子数组 | 59.螺旋矩阵II
java·算法·leetcode·职场和发展
dying_man2 天前
LeetCode--31.下一个排列
算法·leetcode
IC 见路不走2 天前
LeetCode 第75题:颜色分类
数据结构·算法·leetcode
Navigator_Z2 天前
LeetCode //C - 757. Set Intersection Size At Least Two
c语言·算法·leetcode
GalaxyPokemon2 天前
LeetCode - 704. 二分查找
数据结构·算法·leetcode
liuqun03193 天前
开心灿烂go开发面试题
算法·leetcode·golang
এ᭄画画的北北3 天前
力扣-279.完全平方数
数据结构·算法·leetcode
GalaxyPokemon3 天前
LeetCode - LCR 173. 点名
算法·leetcode·职场和发展