본문 바로가기
LeetCode/코딩 테스트 스터디 2주차

[LeetCode] 21. Merge Two Sorted Lists 풀이 (JS)

by inwoo1324 2022. 7. 17.

0. 문제

https://leetcode.com/problems/merge-two-sorted-lists/

 

Merge Two Sorted Lists - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

두 개의 정렬된 정수 리스트를 입력받아, 두 리스트를 이용하여 하나의 정렬된 리스트

#1
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
#2
Input: list1 = [], list2 = []
Output: []
#3
Input: list1 = [], list2 = [0]
Output: [0]

 

1.언어

자바스크립트(JavaScript)

 

2. 문제 풀이

function ListNode(val, next) {
    this.val = (val===undefined ? null : val)
    this.next = (next===undefined ? null : next)
}

var mergeTwoLists = function(list1, list2) {
    
    const res=new ListNode()  //노드 생성
    
    let v1 = 1000, v2 = 1000, // list1,2 value 변수
        res_L=res;  // 노드 얕은 복사
    
    while (list1 !== null || list2 !== null){
        res_L.next = new ListNode(); // 다음 노드 생성
        res_L = res_L.next;
        
        if (v1 == 1000 && list1 != null) v1 = list1.val; //초기 값 && list != null
        if (v2 == 1000 && list2 != null) v2 = list2.val;    
        
        if (v1 < v2){
            res_L.val = v1
            v1 = 1000 
            list1 = list1.next;  //다음 노드로 넘어가기
        } else {
            res_L.val = v2
            v2 = 1000
            list2 = list2.next; //다음 노드로 넘어가기
        }
        
    }
    return res.next
};
Runtime: 85 ms, faster than 73.10% of JavaScript online submissions for Merge Two Sorted Lists.
Memory Usage: 44.4 MB, less than 24.40% of JavaScript online submissions for Merge Two Sorted Lists.
 
역시나 어색한 연결리스트 문제.........
조금 더 많은 문제를 접한 후 다시 풀어볼 문제