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.

這題看了答案,在紙上寫了一遍思路還蠻清晰的。我發現Leetcode自己的solutions里面的高票答案就挺好的(https://discuss.leetcode.com/topic/8976/simple-java-solution-with-clear-explanation)。

思想:

這題思想是一直讓start繞過它后面的節點then,接到then.next上去,然后then接到逆序list的首位,也就是pre.next。

注意的地方:

for循環中的第二句then.next應該指向pre.next,而不是start。
因為start和then一直在向右平移,交換過一次后pre已經不會指向start。

draft
    public ListNode reverseBetween(ListNode head, int m, int n) {
        // we need for nodes
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode start;
        ListNode then;
        for (int i = 0; i < m - 1; i++) {
            pre = pre.next;
        }

        start = pre.next;
        then = start.next;

        for (int i = 0; i < n - m; i++) {//交換n-m次
            start.next = then.next;
            then.next = pre.next; //it has to be pre.next,而不是start,因為start和then一直在向右平移,交換過一次后pre已經不會指向start
            pre.next = then;
            then = start.next;
        }

        return dummy.next;
    }

今天是周五。買了一臺iPhone。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容