题解 | #单链表的排序#

单链表的排序

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,
};

全部评论

相关推荐

点赞 评论 收藏
分享
刘湘_passion:出国旅游?那就小心你的腰子咯
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
04-22 18:57
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务