2.2.2 Reverse LinkedList II

Link: https://oj.leetcode.com/problems/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->NULLm = 2 and n = 4,

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

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

我的思路:remember 需要吧m, n+1這一段提出來反轉。但不知道添加刪除鏈接的先後順序。

寫不出code。重做。

Ref: Dai's code

參考戴的代碼自己寫的:

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        //create a dummy node //why need?
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        //find out the m-1 th node (the one before m-th node)
        ListNode prev = dummy;
        for(int i = 1; i < m && prev != null; i++){
            prev = prev.next;
        }
        if(prev == null) return null;//if there are <= m nodes, return null
        //reverse the nodes between m and n
        ListNode head2 = prev.next;//points to 2
        ListNode cur = head2.next;//3
        for(int i = m; i < n; i++){
            head2.next = cur.next;//2->4
            cur.next = head2;//3->2
            prev.next = cur;//1->3
        }
        return head;
    }
}

正確答案:Time: O(n), Space: O(1)

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        //create a dummy node //why need?
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        //find out the m-1 th node (the one before m-th node)
        ListNode prev = dummy;
        for(int i = 1; i < m && prev != null; i++){
            prev = prev.next;
        }
        if(prev == null) return null;//if there are <= m nodes, return null
        //reverse the nodes between m and n
        ListNode head2 = prev;//points to 1
        prev = head2.next;//2
        ListNode cur = prev.next;//3
        for(int i = m; i < n; i++){
            prev.next = cur.next;//2->4
            cur.next = head2.next;//3->2 //note: here is head2.next, not prev
            head2.next = cur;//1->3
            cur = prev.next;//points to 4
        }
        return dummy.next;
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章