IT/Algorithm

leetCode) 21. Merge Two Sorted Lists

프티 2021. 11. 27. 21:30
반응형

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

 

나의 풀이)

/**
 * 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 listNode = new ListNode(0);
    const headNode = listNode;
    
    while (true) {
        if (!list1) {
            listNode.next = list2;
            break;
        }
        
        if (!list2) {
            listNode.next = list1;
            break;
        }
        
        if (list1.val <= list2.val) {
            listNode.next = list1;
            list1 = list1.next;
        } else {
            listNode.next = list2;
            list2 = list2.next;
        }
        
        listNode = listNode.next;
    }
    
    return headNode.next;
};

ListNode로 만든 노드에 while 문으로 list1과 list2를 하나씩 비교한다음 작은 값부터 next에 집어넣는다.

 

listNode의 첫 번째 노드는 쓸모없는 노드이므로 첫 노드를 참조하는 headNode의 next를 반환한다.

반응형

'IT > Algorithm' 카테고리의 다른 글

leetCode) 35. Search Insert Position  (0) 2021.11.26
프로그래머스) 카펫  (0) 2021.11.26
프로그래머스) 프린터  (0) 2021.11.24
프로그래머스) 구명보트  (0) 2021.11.23
프로그래머스) 큰 수 만들기  (0) 2021.11.21