排序链表

给你链表的头结点 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) => {
    const res = []
    while (head) {
        res.push(head.val)
        head = head.next
    }
    res.sort((x, y) => y - x)
    let cur = null
    res.forEach(i => {
        cur = new ListNode(i, cur)
    })
    return cur
};

  

posted @ 2023-03-01 19:27  671_MrSix  阅读(8)  评论(0编辑  收藏  举报