Sunday, January 15, 2017

Leetcode/F家 -- 92. Reverse Linked List II (Iteration)

92. Reverse Linked List II(Iteration)
medium
https://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->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.
思路: 4 pointers
1. dummy - track head position (dummy.next = head) case: if head is reversed
2. pre - point to the start of the reversed list  (0 to m-1)
3. start -  point to beginning of sub-list to be reversed(itself val unchanged) (0 to n-m swap)
4. then - point  to the node will be reversed(overall traverse the list)


public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head == null||head.next==null) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        for(int i=0;i<m-1;i++)pre = pre.next;
        ListNode start = pre.next, 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;
    }
}

No comments:

Post a Comment