package com.heu.wsq.leetcode.mylinkedlist;
/**
* 92. 反转链表 II
* @author wsq
* @date 2021/3/15
* 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
* 说明:
* 1 ≤ m ≤ n ≤ 链表长度。
*
* 示例:
* 输入: 1->2->3->4->5->NULL, m = 2, n = 4
* 输出: 1->4->3->2->5->NULL
*
* 链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
*/
public class ReverseBetween {
/**
* 增加一个虚拟节点作为哨兵,使得针对头结点进行操作时能够与其他节点逻辑统一
* @param head
* @param left
* @param right
* @return
*/
public ListNode reverseBetween(ListNode head, int left, int right) {
if(head == null || left > right){
return head;
}
ListNode hair = new ListNode(0);
hair.next = head;
ListNode start = null;
ListNode end = null;
ListNode pre = null;
ListNode p = hair;
int n = 0;
while(p != null){
if(n + 1 == left){
pre = p;
start = p.next;
}
if(n == right){
end = p;
break;
}
n++;
p = p.next;
}
ListNode[] arr = reverse(start, end);
pre.next = arr[0];
return hair.next;
}
private ListNode[] reverse(ListNode start, ListNode end){
ListNode prev = end.next;
ListNode curr = start;
while(curr != end){
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
curr.next = prev;
return new ListNode[]{end, start};
}
}
92. 反转链表 II(虚拟节点,增加哨兵统一逻辑)
最新推荐文章于 2025-11-24 15:19:25 发布
本文介绍了一种使用一趟扫描完成链表中指定区间[m,n]反转的方法。通过添加虚拟节点简化了对头节点的操作,并详细展示了如何实现链表的局部反转。
346

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



