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 ≤ mn ≤ length of list.
部分反转链表,细心点处理好各种情况就好

var reverseBetween = function(head, m, n) {
    if (m === n || !head)
        return head;
    var step = m-1;
    var pre = null;
    //将pre指向要反转的前一个
    while (step>0) {
        step--;
        pre = pre ? pre.next : head;
    }
    step = n - m;
    //不反转的末尾
    var ne = pre;
    //反转的开头
    var rb = pre ? pre.next : head;
    pre = rb;
    //要反转的
    var now = pre.next;
    while (step>=1) {
        var temp = now.next;
        now.next = pre;
        pre = now;
        now = temp;
        step--;
    }
    //反转的开头指向后面
    rb.next = now;
    if (ne) {
        //如果ne不是空的,意味着不是从头开始反转的
        //ne指向被反转的链表的末尾
        ne.next = pre;
        return head;
    }   
    //ne是空的,那就意味着整个链表的头是反转链表的末尾
    return pre;
};

你可能感兴趣的:(92. Reverse Linked List II)