题解 | #单链表的排序#

单链表的排序

https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08

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

/**
 *
 * @param head ListNode类 the head node
 * @return ListNode类
 */
function sortInList(head) {
    // write code here
    let arr = [];

    while (head) {
        arr.push(head.val);
        head = head.next;
    }

    quickSort(arr, 0, arr.length - 1);

    let res = new ListNode(-1),
        t = res;
    for (let i = 0; i < arr.length; i++) {
        let node = new ListNode(arr[i]);
        t.next = node;
        t = t.next;
    }

    return res.next;
}

function quickSort(arr, s, t) {
    let left = s + 1,
        right = t,
        x = arr[s];
    while (left <= right) {
        while (left <= right && arr[left] <= x) left++;
        while (left <= right && arr[right] >= x) right--;
        if (left < right) {
            let t = arr[left];
            arr[left] = arr[right];
            arr[right] = t;
            left++;
            right--;
        }
    }

    if (s != right) {
        arr[s] = arr[right];
        arr[right] = x;
    }

    if (s < right - 1) quickSort(arr, s, right - 1);
    if (t > right + 1) quickSort(arr, right + 1, t);
}

module.exports = {
    sortInList: sortInList,
};

全部评论

相关推荐

nus22016021404:兄弟,你这个简历撕了丢了吧,就是一坨,去找几个项目,理解项目流程,看几遍就是你的了,看看八股就去干了,多看看牛客里别人发出来的简历,对着写,你这写的啥啊,纯一坨
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-19 20:55
因为业务不是喜欢的,所以就没去,现在实习工作也有很多dirtywork,很后悔,怎么能舔回这个offer啊
flmz_Kk:试一试跟hr舔回来,不过保不齐米的活也有很多dirtywork,只能说不要美化自己没走过的路
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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