Friday, November 6, 2015

[leetcode]Reverse Linked List II

Again, use example diagram to think of the solution.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode previous = dummy;
        ListNode current = head;
        for (int i = 1; i < m; i++){
            previous = current;
            current = current.next;
        }
        ListNode front = previous; 
        ListNode tail = current;
        previous = current;
        current = current.next;
        for (int i = m; i < n; i++){
            ListNode next = current.next;
            current.next = previous;
            previous = current;
            current = next;
        }
        
        front.next = previous;
        tail.next = current;
        return dummy.next;
    }
}

No comments:

Post a Comment