Saturday, March 11, 2017

Reverse Linked List II

一直有一个误区就是reverse的时候是把curr的前后指针对调
然而在iteration中只负责把当前curr:
1.记住next = curr.next
2.curr.next = prev;
3.prev = curr, curr = next
也就是说只把当前Node的next改变,默认它的prev.next是属于上一个case的,它的next.next是属于下一个case的

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null || head.next == null || m == n) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;
        for (int i = 0; i < m - 1; i++) {
            prev = prev.next;
        }
       
        //return the head of the residual
        ListNode temp = reverseKNodes(prev.next, n - m + 1);
        prev.next = temp;
        return dummy.next;
    }
    private ListNode reverseKNodes(ListNode head, int k) {
        //System.out.println(k);
        ListNode prev = null;
        ListNode curr = head;
        ListNode next = null;
        for (int i = 0; i < k; i++) {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        head.next = curr;
        //System.out.println(prev.val);
        return prev;
    }
   
}

No comments:

Post a Comment