92. Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

** 解題思路 **
先用dummy node來記錄鏈表的起始點(diǎn), 再找到第m個(gè)節(jié)點(diǎn)- start, 和它后續(xù)的節(jié)點(diǎn) then, 然后用pre, start , then 在for 循環(huán)中實(shí)現(xiàn)(m-n)子鏈表的反轉(zhuǎn)即可。

Simply just reverse the list along the way using 4 pointers: dummy, pre, start, then
參考: reverse using 4 pointers

    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;  // create the dummy node to mark the head of this list
        
        ListNode pre = dummy;  // make a pointer pre as a marker for the node before reversing
        for (int i = 0; i < m - 1; i++) {
            pre = pre.next;
        }
        
        ListNode start = pre.next;    // a pointer to the beginning of a sub-list that will be reversed
        ListNode then = start.next; // a pointer to the node will be reversed
        
        // 1->2->3->4->5; m = 2; n = 4  ---> pre = 1, start = 2, then = 3
        // dummy -> 1 ->2 ->3 ->4 ->5
        for (int i = 0 ; i < n - m; i++) {
            start.next = then.next;
            then.next = pre.next;
            pre.next = then;
            then = start.next;
        }
        // first reversing : dummy->1 - 3 - 2 - 4 - 5; pre = 1, start = 2, then = 4
        // second reversing: dummy->1 - 4 - 3 - 2 - 5; pre = 1, start = 2, then = 5 (finish)
        return dummy.next;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容