본문 바로가기
Coding Test/LeetCode

[Javascript] (LeetCode) 21. Merge Two Sorted Lists (Easy)

by Chaedie 2022. 8. 9.
728x90

[Javascript] (LeetCode) 21. Merge Two Sorted Lists (Easy)

💡 구글에 Javascript 풀이가 많이 없거나, 배운 점이 있으면 포스팅합니다.

다른 사람 풀이 참고한 내 풀이

/**
 * 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) {  

  // null Node 세팅
  let head = new ListNode(0, null);
  let curNode = head;  

  // 앞으로 나가면서, 비교하면서 연결해줄거임
  while(list1 && list2) {
    if (list1.val <= list2.val) {
      curNode.next = list1;
      list1 = list1.next;
    } else {
      curNode.next = list2;
      list2 = list2.next;
    }
    curNode = curNode.next;
  }

  curNode.next = list1 || list2;

  return head.next;
};
  • 도저히 안풀려서 다른 사람 풀이 보고 풀었습니다. 사실상 거의 다 받아 적은 느낌이네요 ㅠ

배운 점, 느낀 점

  • 1) 우선 let head = new ListNode(0, null); return head.next; 로 하는방법을 배웠습니다.
    • 제 코드에선 list1, list2 밸류 비교해서 작은 놈을 head로 삼는 방법을 택했는데 위 방법이 훨씬 깔끔하네요.
  • 2) while (list1 && list2) {...} => [curNode.next](http://curNode.next) = list1 || list2 하는 방법을 배웠습니다.
    • 저는 while (list1 || list2) {...} 로 해서 자꾸 “Cannot set property of null” 에러가 떴었습니다 ㅠ
  • 결론) 더 많이 풀어 보자.
  • 여담) 웹 개발에 별로 필요없을 것 같은 linked list지만 컴퓨팅 사고에는 도움이 엄청 되는것 같습니다. 아침마다 1문제씩 푸는 게 루틴인데 아침마다 정말 머리가 빠개질것 같거든요 ㅎㅎ 제발 정복 좀 해보자 😭

2일 뒤인 오늘 다시 풀어본 결과 (8.12일)

/**
 * 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) {  
  
  const head = new ListNode(0, null);
  let ahead = head;
  
  while(list1 && list2) {
    if (list1.val < list2.val) {
      ahead.next = list1;
      list1 = list1.next;
    } else {
      ahead.next = list2;
      list2 = list2.next;
    }
    ahead = ahead.next;
  }
  
  while (list1) {
    ahead.next = list1;
    list1 = list1.next;
    ahead = ahead.next;
  }
  while (list2) {
    ahead.next = list2;
    list2 = list2.next;
    ahead = ahead.next;
  }
  
  
  return head.next;
};
  • while문으로 다 확인 한 뒤 나머지 애들 확인하는 과정에서
    • 다른 사람 참고한 풀이는 list1 || list2 의 형태로 나머지를 처리해줬고, (1번만에 전부)
    • 제 코드는 다시 각각 while로 같은 방식으로 끝까지 찾아갔네요.
    • 사실 다른 list에 남은 데이터가 없다면 끝까지 찾을 필요가 없고, 한번 연결해줌으로 끝낼수 있는데, 깊게 생각하지 못했네요.
    • 그래도 안보고 풀어서 다행 ㅎㅎ

댓글