Skip to content

Commit e308672

Browse files
committed
merge-two-sorted-lists solution
1 parent 11df4e1 commit e308672

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} list1
10+
* @param {ListNode} list2
11+
* @return {ListNode}
12+
*/
13+
var mergeTwoLists = function(list1, list2) {
14+
// ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ์˜ ์‹œ์ž‘์ ์„ ์œ„ํ•œ ๋”๋ฏธ ๋…ธ๋“œ
15+
let dummy = new ListNode(-1);
16+
let current = dummy;
17+
18+
// ๋‘˜ ๋‹ค null์ด ์•„๋‹ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต
19+
while (list1 !== null && list2 !== null) {
20+
if (list1.val <= list2.val) {
21+
current.next = list1;
22+
list1 = list1.next;
23+
} else {
24+
current.next = list2;
25+
list2 = list2.next;
26+
}
27+
current = current.next;
28+
}
29+
30+
// ๋‚จ์€ ๋…ธ๋“œ๊ฐ€ ์žˆ์œผ๋ฉด ๊ทธ๋Œ€๋กœ ๋ถ™์ž„
31+
current.next = list1 !== null ? list1 : list2;
32+
33+
return dummy.next; // dummy ๋‹ค์Œ์ด ์ง„์งœ head
34+
};

0 commit comments

Comments
ย (0)