import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param left int整型
* @param right int整型
* @return ListNode类
*/
public ListNode reverseBetween (ListNode head, int left, int right) {
// write code here
// 1. 特殊情况的处理
if (head == null || head.next == null || left == right) return head;
// 2. 为了避免边界问题的难处理性,此处引入一个新的头,让“边界”不再是“边界”
ListNode newHead = new ListNode(-1);
newHead.next = head;
// 3. 先找到要反转的前驱节点
ListNode pre = newHead;
// ListNode cur = newHead;
int L = left;
while (L-- != 1) {
pre = pre.next;
}
// 4. 开始反转
ListNode start = pre.next;
ListNode end = start; // 记录开始反转的点,后续需要与剩余部分拼接
ListNode cur = start.next;
int count = right - left;
while(count-- != 0) {
ListNode next = cur.next;
cur.next = start;
start = cur;
cur = next;
}
// 5. 走到此处链表如图:newHead pre start end cur 链表结尾
// 创建的新头节点 原来的right left
pre.next = start;
end.next = cur;
// 6. 返回节点即可
return newHead.next;
}
}