92. 反转链表 II
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
思路
这个思路是用穿针法
注意引入了一个dummynode使得操作简单了
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
int cnt = 1;
while(pre.next != null && cnt < left) {
pre = pre.next;
cnt++;
}
ListNode cur = pre.next;
ListNode tail = cur;
ListNode nxt = null;
while (cur != null && cnt <= right) {
nxt = cur.next;
cur.next = pre.next;
pre.next = cur;
tail.next = nxt;
cur = nxt;
cnt++;
}
return dummy.next;
}