当前位置:网站首页>反转链表II
反转链表II
2022-04-22 08:17:00 【学海无涯苦作舟呀】
题目链接:https://leetcode-cn.com/problems/reverse-linked-list-ii/
题目:给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。

解题思路:在需要反转的区间里,每遍历到一个节点,让这个新节点来到反转部分的起始位置。接下来画图来展示了整个流程。
pre:永远指向待反转区域的第一个节点 left 的前一个节点,在循环过程中不变
cur:指向待反转区域的第一个节点 left
next:永远指向 cur 的下一个节点,循环过程中,cur变化以后 next 会跟着变化
附上手写版思路:

代码如下:
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummuNode = new ListNode(-1);//哨兵节点
dummuNode.next = head;
ListNode pre = dummuNode;
for(int i = 0;i<left -1;i++) pre = pre.next;//pre移动left-1次,到达指定位置
ListNode cur = pre.next;
ListNode next;
for(int i = 0;i<right -left;i++){
//以下代码需要自己动手画图,就很清楚了
next = cur.next;//先变动next
cur.next = next.next;
next.next = pre.next;
pre.next = next;
}
return dummuNode.next;
}
}
版权声明
本文为[学海无涯苦作舟呀]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_46184836/article/details/124285378
边栏推荐
猜你喜欢

關於我想借款卻被騙了一萬五這件事

找工作、写简历到面试,这套资料就够了!

选择排序及优化

==And equals

How does CSDN reprint other people's blogs

Fabric test example, encountered order exited (x) x seconds

Rhel7 - process management

Mycms self media CMS system v3 2.2. Advertisement plug-in optimization

Scope and lifecycle of variables

QT file reading and writing practical tutorial
随机推荐
14个py小游戏 源代码分享
RHEL7 逻辑卷管理-笔记
First knowledge of C language ~ circular statement
The server is set to start automatically and regularly
关于我想借款却被骗了一万五这件事
POI operation excel three swordsman
【微信小程序】为小程序设置底部菜单(tabBar)
Redhat7 configuration yum
About the fact that I was cheated of fifteen thousand when I wanted to borrow money
CPU memory access space
Insert sorting and optimization
Quick sequencing and optimization
RHEL user and group management - Notes
Selection, sorting and optimization
How does CSDN reprint other people's blogs
const修饰变量
Flume composition, put transaction, take transaction
Android Development - SQLite and sqlitedatabase Application Experiment 6 notes
虾皮二面:什么是零拷贝?如何实现零拷贝?
C语言的学习目标和大致内容