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

相关推荐
前端拿破轮19 分钟前
🤡🤡🤡面试官:就你这还每天刷leetcode?连四数相加和四数之和都分不清!
算法·leetcode·面试
无聊的小坏坏2 小时前
单调栈通关指南:从力扣 84 到力扣 42
c++·算法·leetcode
许小燚11 小时前
线性表——双向链表
数据结构·链表
晚云与城14 小时前
【数据结构】顺序表和链表
数据结构·链表
FirstFrost --sy15 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
liulilittle16 小时前
LinkedList 链表数据结构实现 (OPENPPP2)
开发语言·数据结构·c++·链表
qq_5139704417 小时前
力扣 hot100 Day37
算法·leetcode
不見星空18 小时前
leetcode 每日一题 1865. 找出和为指定值的下标对
算法·leetcode
chao_78921 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
GEEK零零七21 小时前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode