当前位置:网站首页>LeetCode 92. 反转链表 II
LeetCode 92. 反转链表 II
2022-08-10 11:09:00 【水菜笔】
原题网址:https://leetcode.cn/problems/reverse-linked-list-ii/
给一个链表,翻转一个区间内的节点。
找到左区间的前一个节点,然后开始删除节点,直到出了区间;最后拼接翻转的链表和剩下的链表;
public ListNode reverseBetween(ListNode head, int left, int right) {
if(head == null || head.next == null || left == right) {
return head;
}
// 如果left是第一个数据,无法找到它的前一个,所以引用虚拟节点
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
// 通过找前一个节点,删除left节点
ListNode prev = null;
ListNode first = null;
ListNode tail = null;
ListNode cur = dummyHead;
for(int i=0;i<right;i++) {
// 找到left的前一个节点了,开始删除。
if(i>=left-1) {
prev = cur;
ListNode node = prev.next;
prev.next = node.next;
if(first == null) {
first = tail = node;
} else {
node.next = first;
first = node;
}
} else {
cur = cur.next;
}
}
tail.next = prev.next;
prev.next = first;
return dummyHead.next;
}
边栏推荐
猜你喜欢
随机推荐
mysql appears: ERROR 1524 (HY000): Plugin '123' is not loaded
A little self-deprecating deconstruction about farmers "code"
微信小程序提交审核历史版本记录从哪里查看
Licking Exercise - 59 From Binary Search Trees to Greater Sum Trees
4 of huawei offer levels, incredibly side is easing the bit in the interview ali?
Some tips for using Unsafe
Open Office XML 格式里如何描述多段具有不同字体设置的段落
HDU 4372:Count the Buildings (Stirling数)
Buckle exercise - rectangular area does not exceed the maximum value of K and (hard)
项目部署、
CPU多级缓存与缓存一致性
力扣练习——61 根据字符出现频率排序
石墨文档打开文档时快速定位到上次写的位置
单目操作符(含原码反码补码转换)
模块九 - 设计电商秒杀系统
Interviewer: How are Dao, Service, Controller, Util, and Model divided in the project?
实现内网穿透的最佳解决方案(无实名认证,完全免费)
快手“弃”有赞与微盟“结亲”,电商SaaS行业竞争格局将变?
HDU 1520 Anniversary party (树型dp)
振弦传感器及核心VM系列振弦采集模块









