码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 92 Reverse Linked List II

时间:2015-06-28 15:26:13      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

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 92 Reverse Linked List II

标签:

原文地址:http://www.cnblogs.com/lilixu/p/4605493.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!