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

相关推荐
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——点名
数据结构·算法·leetcode·c/c++
愚润求学4 小时前
【动态规划】专题完结,题单汇总
算法·leetcode·动态规划
·白小白6 小时前
力扣(LeetCode) ——43.字符串相乘(C++)
c++·leetcode
FMRbpm6 小时前
链表5--------删除
数据结构·c++·算法·链表·新手入门
遗憾是什么.8 小时前
数据结构 -- 栈
数据结构·算法·链表
liuhuapeng03049 小时前
GetMapping自动截取List<String>字符
数据结构·windows·list
一匹电信狗10 小时前
【C++11】Lambda表达式+新的类功能
服务器·c++·算法·leetcode·小程序·stl·visual studio
在等晚安么10 小时前
力扣面试150题打卡
算法·leetcode·面试
User_芊芊君子13 小时前
【LeetCode经典题解】递归破解对称二叉树之谜
算法·leetcode·职场和发展
Rock_yzh13 小时前
LeetCode算法刷题——49. 字母异位词分组
数据结构·c++·学习·算法·leetcode·职场和发展·哈希算法