PS/LeetCode

LeetCode / Linked List / 148번 / Sort List / JS

KimMinJun 2023. 4. 28. 17:19

< 문제 바로가기 >

 

Sort List - LeetCode

Can you solve this real interview question? Sort List - Given the head of a linked list, return the list after sorting it in ascending order.   Example 1: [https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg] Input: head = [4,2,1,3] Output: [1,

leetcode.com

 

< 문제 간단설명 >

리스트에 있는 노드들을 오름차순으로 정렬하는 문제이다.

 

/**
 * 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}
 */
var sortList = function(head) {
    if(!head) {
        return null;
    }

    let result = [];

    // 모든 노드를 배열에 넣음
    while(head) {
        result.push(head);
        head = head.next;
    }

    // 노드의 value 값으로 오름차순 정렬
    result.sort((a, b) => a.val - b.val);

    // 리스트에 들어있는 노드들을 연결시켜줌
    for(let i=0; i<result.length; i+=1) {
        result[i].next = result[i + 1] || null;
    }

    return result[0];
};