[LeetCode]92. Reverse Linked List II反转部分链表

时间:2025-04-27 09:07:31
/*
重点还是反转链表
思路就是中间的反转,然后两头接上
*/
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head==null||m>=n) return head;
int count = 1;
ListNode sta = head;
//mid就是第一个接点的前节点
ListNode mid = null;
while (count<m)
{
mid = head;
head = head.next;
count++;
}
//中间的部分反转,此时的head是反转的开头
ListNode pre = null;
while (count<=n)
{
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
count++;
}
//将后边的接上
ListNode end = pre;
while (end.next!=null) end = end.next;
end.next = head;
//如果是从第一个开始,要单独考虑
if (mid!=null) mid.next = pre;
else return pre;
return sta;
}