首页 > 其他 > 详细

【链表】 Reverse Linked List II

时间:2016-01-19 23:36:31      阅读:274      评论: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.

思路:

找到m节点,从节点m到n依次反转指针,然后把翻转后的串连起来即可

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} m
 * @param {number} n
 * @return {ListNode}
 */
var reverseBetween = function(head, m, n) {
    if(head==null){
        return head;
    }
    
    var p=head,mpre=null;
    var tempHead=new ListNode(0);
    tempHead.next=head;
    mpre=tempHead;
    for(var i=1;i<m;i++){
        mpre=p;
        p=p.next;
    }
    
    var pre=null,cur=null,next=null;
    var tempp=p;
    for(var i = 1; i <= n-m; i++){//反转m到n的指针
        pre = p;
        cur = p.next;
        next = cur.next;
        cur.next = pre;
        p=cur;
    }
    mpre.next=p;
    tempp.next=next;
    head=tempHead.next;
    tempHead=null;
    return head;
};

 

【链表】 Reverse Linked List II

原文:http://www.cnblogs.com/shytong/p/5143669.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!