题解 | #重排链表#

重排链表

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

全部评论

相关推荐

不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 12:10
直接上图
牛客13578115...:改得一般,不值80
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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