[leetcode, JS] 21. Merge Two Sorted Lists

mxxn·2023년 8월 4일
0

leetcode

목록 보기
8/198

문제

문제 링크 : Merge Two Sorted Lists

풀이

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function(list1, list2) {
    let List = new ListNode(0);
    let head = List;
    let sortedArr = []
    while(list1 !== null || list2 !== null){
        if(list1 !== null) {
            sortedArr.push(list1.val)
            list1 = list1.next
        }
        if(list2 !== null ) {
            sortedArr.push(list2.val)
            list2 = list2.next
        } 
        
    }
    sortedArr.sort( (a,b) => (a-b) )
    for(let i=0; i<sortedArr.length; i++){
        head.next = new ListNode(sortedArr[i])
        head = head.next
    }
    return List.next
};
  1. list1과 list2를 while문을 통해 sortedArr에 val를 담고
  2. sortedArr에서 sort를 한 후에, List에 다시 담는 과정
  • Runtime 57 ms, Memory 44.4 MB

다른 풀이

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function(a, b) {
    var c = root = {val:0, next:null}
    while (true) {
        if (a===null) {c.next=b; return root.next}
        if (b===null) {c.next=a; return root.next}
        if (a.val < b.val) {c=c.next=a; a=a.next}
        else               {c=c.next=b; b=b.next}
    }
};
  1. while문 안에서 list1의 val과 list2의 val을 비교하여 sort
  2. list1이나 list2나 null이 되면 나머지 next를 그대로 이어서 return
  • Runtime 54 ms, Memory 44.2 MB
profile
내일도 글쓰기

0개의 댓글