Leetcode 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->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.

要求在1*n时间内完成

类似于Leetcode 206 Reverse Linked List

保存指针指向倒置链表段的前一个node,在倒置结束后连接其下一个node。

var reverseBetween = function(head, m, n) {

    if(m===n) return head

    var dummy = new ListNode()

    dummy.next = head

    var p = dummy

    for(var i=0;i<m-1;i++) 

        p = p.next

    var c = p.next

    var r = null

    for(var i=0;i<n-m+1;i++){

        var nextnode = c.next

        c.next = r

        r = c

        c = nextnode

    }

    p.next.next = c

    p.next = r

    return dummy.next

}

 

你可能感兴趣的:(LeetCode)