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

相关推荐
设计师小聂!21 分钟前
力扣热题100------21.合并两个有序链表
算法·leetcode·链表
এ᭄画画的北北1 小时前
力扣-1.两数之和
数据结构·算法·leetcode
快去睡觉~3 小时前
力扣301:删除无效的括号
数据结构·算法·leetcode
闪电麦坤954 小时前
数据结构:反转链表(reverse the linked list)
数据结构·链表
ikkkkkkkl5 小时前
LeetCode:15.三数之和&&18.四数之和
c++·算法·leetcode
屁股割了还要学5 小时前
【数据结构入门】链表
c语言·开发语言·数据结构·c++·学习·算法·链表
恣艺6 小时前
LeetCode 135:分糖果
算法·leetcode·职场和发展
焊锡与代码齐飞9 小时前
嵌入式第十八课!!数据结构篇入门及单向链表
c语言·数据结构·学习·算法·链表·排序算法
刃神太酷啦12 小时前
C++ 容器适配器与核心数据结构精解:栈、队列、deque 底层实现与实战应用----《Hello C++ Wrold!》(17)--(C/C++)
java·c语言·数据结构·c++·qt·算法·leetcode
AWEN_3313 小时前
最大重复子字符串
leetcode