92. 反转链表 II
https://leetcode.cn/problems/reverse-linked-list-ii/
难度中等1382
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:

输入:head = [1,2,3,4,5], left = 2, right = 4 输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1 输出:[5]
提示:
- 链表中节点数目为
n 1 <= n <= 500-500 <= Node.val <= 5001 <= left <= right <= n
进阶: 你可以使用一趟扫描完成反转吗?
通过次数334,001提交次数601,179
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
// 一次遍历
ListNode node = new ListNode();
node.next = head;
head = node;
int i=1;
ListNode end=null;
while(node!=null)
{
if(i<left)
{
i++;
node = node.next;
}
else if(i>=left && i<right)
{
if(i==left) end = node.next;
ListNode temp = end.next;
end.next = temp.next;
temp.next = node.next;
node.next = temp;
i++;
}
else if(i==right)
{
// end.next = temp;
// System.out.println(temp.val);
return head.next;
}
}
return head.next;
}
}


该篇博客介绍了如何在给定的链表中,根据给定的左右位置,反转链表的指定部分。提供的解决方案通过一次遍历实现反转,涉及链表节点的重新连接操作。示例展示了如何反转从位置2到位置4的链表节点,并给出了相关提示和代码实现。
1133

被折叠的 条评论
为什么被折叠?



