LeetCode #21 Merge Two Sorted Lists

ieunjung·2020년 9월 27일

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

문제파악

Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
연결리스트 2개를 합쳐서 한 개로 만들어라.

예제

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

연결리스트에서 노드를 한 개씩 크기를 비교하면서 새로운 리스트를 만들어준다.
head를 옮겨가면서 노드를 연결한다.

코드

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function(l1, l2) {
    let list = new ListNode(-1, null),
        mergedHead = list;
    
    while(l1 && l2){
        if(l1.val > l2.val){
            mergedHead.next = l2;
            l2 = l2.next;
        }else{
            mergedHead.next = l1;
            l1 = l1.next;
        }
        mergedHead = mergedHead.next; // head 이동
    }
    mergedHead.next = l1 || l2; // 마지막 노드 처리
    
    return list.next;
};
profile
Done is better than perfect

0개의 댓글