Problem: 92. 反转链表 II
- 特殊情况
Java
/**
* 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 {
ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy = new ListNode(0, head);//
ListNode p0 = dummy;
for(int i = 0; i < left - 1; i++)
p0 = p0.next;
ListNode pre = null;
ListNode cur = p0.next; // 局部链表的第一个节点
// 循环反转局部的链表
for(int i = 0; i < right - left + 1; i++)
{
ListNode nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
// 处理局部链表的首尾与整体链表的衔接
p0.next.next = cur;// p0.next 是局部链表的第一个节点
p0.next = pre;//pre 局部链表的最后一个节点
return dummy.next;
}
}