92. Reverse Linked List II
Solution
這題有點要用背的
先建立一個dummy node 其next 指向 head
然後找到要開始轉的node的前一個設定為pre,
pre.next就是start。然後start.next就是then
透過pre, start, then這三個node之間的運作把list 局部reverse 進行(n-m)次

public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
for(int i = 1 ; i < m ; i ++){
pre = pre.next;
}
ListNode start = pre.next;
ListNode then = start.next;
for(int i = 0; i < (n-m); i++){
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}
return dummy.next;
}
Last updated
Was this helpful?