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

相关推荐
.小小陈.5 小时前
C++初阶9:list使用攻略
开发语言·c++·学习·list
lightqjx6 小时前
【算法】双指针
c++·算法·leetcode·双指针
sin_hielo6 小时前
leetcode 2147
数据结构·算法·leetcode
萌>__<新7 小时前
力扣打卡每日一题——缺失的第一个正数
数据结构·算法·leetcode
萌>__<新7 小时前
力扣打卡每日一题————零钱兑换
算法·leetcode·职场和发展
重生之后端学习7 小时前
238. 除自身以外数组的乘积
java·数据结构·算法·leetcode·职场和发展·哈希算法
Learner__Q8 小时前
每天五分钟:动态规划-LeetCode高频题_day2
算法·leetcode·动态规划
Dream it possible!10 小时前
LeetCode 面试经典 150_字典树_添加与搜索单词 - 数据结构设计(96_211_C++_中等)
c++·leetcode·面试·字典树
带鱼吃猫11 小时前
数据结构:单链表 / 双链表的结构、接口实现与顺序表对比
数据结构·链表