Skip to content

Commit

Permalink
solve: merge two sorted lists
Browse files Browse the repository at this point in the history
  • Loading branch information
wogha95 committed Sep 29, 2024
1 parent 7718d7b commit 6e1c133
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions merge-two-sorted-lists/wogha95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/**
* TC: O(List1 + List2)
* List1, List2 ์ „์ฒด ์ˆœํšŒ 1๋ฒˆ์”ฉ ํ•ฉ๋‹ˆ๋‹ค.
*
* SC: O(1)
* List1, List2์˜ ๊ธธ์ด์™€ ๋ฌด๊ด€ํ•œ ๊ณ ์ •๋œ ๋ฐ์ดํ„ฐ ๊ณต๊ฐ„์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. (head, pointer ๋ณ€์ˆ˜๋“ค)
*
* List1: list1.length, List2.length;
*/

/**
* 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) {
// 1. ๋‘˜ ์ค‘ ํ•˜๋‚˜์˜ list๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ ๋ฐ˜๋Œ€ํŽธ์˜ list๋ฅผ ๋ฐ˜ํ™˜
if (!list1) {
return list2;
}
if (!list2) {
return list1;
}

// 2. ์ •๋‹ต์„ ๋ฐ˜ํ™˜ํ•  ์‹œ์ž‘์ (head)์™€ list ์ˆœํšŒ์‹œ ํ•„์š”ํ•œ pointer
const head = new ListNode();
let headPointer = head;
let list1Pointer = list1;
let list2Pointer = list2;

// 3. ๋‘ list ๋ชจ๋‘ ๋…ธ๋“œ๋ฅผ ๊ฐ€์ง„ ๊ฒฝ์šฐ
while (list1Pointer && list2Pointer) {
if (list1Pointer.val < list2Pointer.val) {
list1Pointer = connectHeadAndListPointer(list1Pointer);
} else {
list2Pointer = connectHeadAndListPointer(list2Pointer);
}
}

// 4. ํ•œ์ชฝ list์˜ ๋‚จ์€ ๋…ธ๋“œ ์—ฐ๊ฒฐ
while (list1Pointer) {
list1Pointer = connectHeadAndListPointer(list1Pointer);
}

while (list2Pointer) {
list2Pointer = connectHeadAndListPointer(list2Pointer);
}

return head.next;

// 5. head์˜ list๋กœ ์—ฐ๊ฒฐ ํ›„ ๋‹ค์Œ ๋…ธ๋“œ๋กœ pointer ์ด๋™
function connectHeadAndListPointer(listPointer) {
headPointer.next = listPointer;
listPointer = listPointer.next;
headPointer = headPointer.next;

return listPointer;
}
};

0 comments on commit 6e1c133

Please sign in to comment.