链表排序

给定链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
const sortList = (head) => {
    if (!head) return head
    const res = []
    while (head) {
        res.push(head.val)
        head = head.next
    }
    res.sort((x, y) => x - y)
    let cur = undefined
    let i = res.length
    while (--i > -1) {
        cur = new ListNode(res[i], cur)
    }
    return cur
};

  

posted @ 2023-02-08 17:40  671_MrSix  阅读(7)  评论(0编辑  收藏  举报