[Leet Code] Merge Two Sorted Lists

Hemudi | Hemdi·2021년 11월 26일
0

🧨 코딩테스트

목록 보기
19/19
post-thumbnail

주어진 두 개의 정렬된 연결리스트를 오름차순으로 병합하는 함수


✳️ 제한사항


✳️ 예시

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


✳️ 내가 푼 코드

💟 반복문

var mergeTwoLists = function(list1, list2){
    let currentNode = new ListNode();
    let headNode = currentNode;
    
    while(list1 !== null && list2 !== null){
        if(list1.val < list2.val){
            currentNode.next = list1;
            list1 = list1.next;
        } else {
            currentNode.next = list2;
            list2 = list2.next;
        }

        currentNode = currentNode.next;
    }

    currentNode.next = list1 !== null ? list1 : list2;
    return headNode.next;
}

💟 재귀함수

var mergeTwoLists = function(list1, list2){
    if(list1 === null) return list2;
    if(list2 === null) return list1;

    if(list1.val < list2.val){
        list1.next = mergeTwoLists(list1.next, list2);
        return list1;
    }

    list2.next = mergeTwoLists(list1, list2.next);
    return list2;
}

✳️ 생각 정리

  • 입력값을 제대로 이해를 못해서 힘들었다.
  • 옛날에 연결리스트 공부했던걸로 떠듬떠듬 반복문을 이용해서 풀었다.
  • 근데 currentNode 의 정보를 초반에 따로 저장을 안해놔서 다 돌리고 난 다음에 그러고보니 처음 값은 어떻게 찾지?! 하고 당황했다.
  • 그래서 고민하다가 결국 다른 분들 코드를 슬쩍 봤고 초반에 따로 head = current 하고 저장해두는거 보고 이마 탁 했음. 다 풀어놓고 막판에ㅠ 멍청ㅠ
  • 그렇게 코드들 슬쩍 보다가 누가 댓글에 재귀 함수로 풀 수 있다고 하길래 그 코드는 보지 않고 나도 재귀함수로 한번 풀어봤다.
profile
'햄디'로 현재 코드스쿼드 코코아 과정 수강 중 💻 (티스토리로 이전)

0개의 댓글