题解 | #重排链表#

重排链表

http://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b

 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */

/**
 * 
 * @param head ListNode类 
 * @return void
 */
function reorderList( head ) {
    // write code here
    if(!head || !head.next||!head.next.next){
        return head
    }
    let fast = head,slow = head
    while(fast && fast.next && fast.next.next){
        fast = fast.next.next
        slow = slow.next
    }
    let res = reverse(slow.next)
    slow.next = null
    let ans = head,p1 = ans,p2 = res
    while(ans && res){
        p1 = ans.next
        p2 = res.next
        ans.next = res
        res.next = p1
        ans = p1
        res = p2
    }
    return head
}
function reverse(head){
    let cur = null
    let pre = null
    while(head){
        cur = head.next
        head.next = pre
        pre = head
        head = cur
    }
    return pre
}

module.exports = {
    reorderList : reorderList
};

alt


/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */

/**
 * 
 * @param head ListNode类 
 * @return void
 */
function reorderList( head ) {
    // write code here
    if(!head || !head.next||!head.next.next){
        return head
    }
    let arr = []
    while(head){
        arr.push(head)
        head = head.next
    }
    let i = 0,j = arr.length - 1
    while(i < j){
        arr[i].next = arr[j]
        i++
        if(i===j)    break
        arr[j].next = arr[i]
        j--
    }
    arr[i].next = null
    return arr[0]
}
module.exports = {
    reorderList : reorderList
};

alt

全部评论

相关推荐

09-14 17:23
门头沟学院
故事和酒66:所以说副业很重要,程序员干到40岁,再怎么也赚300万了,吃吃利息也够活下去
点赞 评论 收藏
分享
09-01 11:31
门头沟学院 Java
buul:七牛云的吧,感觉想法是好的,但是大家没那么多时间弄他这个啊。。。不知道的还以为他是顶尖大厂呢还搞比赛抢hc,只能说应试者的痛苦考察方是无法理解的,他们只会想一出是一出
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务