ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

Linked List + Merge Sort

Merge sort์˜ ๊ธฐ๋ณธ๊ฐœ๋…์€ Divide and conquer์ด๋‹ค.
๋”ฐ๋ผ์„œ Quick sort์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์žฌ๊ท€๋ฅผ ํ†ตํ•ด ๊ตฌํ˜„ ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์ด๋ฏธ ์ •๋ ฌ๋œ ๋‘ ํŒŒํ‹ฐ์…˜๋“ค์ด ์žˆ๋‹ค๋ฉด,
๋‘ ํŒŒํ‹ฐ์…˜์˜ ์ฒซ์š”์†Œ๋ฅผ ๊ฒ€์‚ฌํ•˜์—ฌ ๋” ์ž‘์€ ์š”์†Œ๋ฅผ ๋บ€๋‹ค.

Linked List ์™€ ์—ฐ๊ฒฐํ•˜์—ฌ์„œ ํ‘ธ๋Š” ๋ฌธ์ œ์ด๊ธฐ๋•Œ๋ฌธ์—
๋” ์ž‘์€ ์š”์†Œ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๋ง๋ฆฌ๋ฅผ ํ—ค๋“œ๋กœ ์‚ผ๊ณ , 
ํ—ค๋“œ๋กœ ์‚ผ์€ ๋ง๋ฆฌ์˜ ๋‹ค์Œ ๋…ธ๋“œ์™€, ํ—ค๋“œ๊ฐ€ ๋˜์ง€๋ชปํ•œ ๋ง๋ฆฌ ๋‘๊ฐ€์ง€๋ฅผ ๋‹ค์‹œ ํ•จ์ˆ˜์— ๋„ฃ๋Š”๋‹ค.

21. 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.

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

/**
 * 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}
 */

const mergeTwoLists = function(l1, l2) {
  if (!l1) return l2;
  if (!l2) return l1;

  if(l1.val < l2.val) {
    l1.next = mergeTwoLists(l1.next, l2);
    return l1;
  } else {
    l2.next = mergeTwoLists(l1, l2.next);
    return l2;
  }
};

 

์ถœ์ฒ˜ : leetcode.com/problems/merge-two-sorted-lists/

๋Œ“๊ธ€