Skip to content

Commit a38f14d

Browse files
committed
merge-two-sorted-lists
1 parent 5dab9e3 commit a38f14d

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+
const answer = new ListNode();
15+
let temp = answer; // answer은 head를 가지고 있어야함
16+
17+
// list1, list2 중 하나라도 끝까지 도달할 때 까지 루프 돌리기
18+
while (list1 && list2) {
19+
// 더 작은수를 가진 리스트를 연결
20+
if (list1.val < list2.val) {
21+
temp.next = list1;
22+
list1 = list1.next;
23+
} else {
24+
temp.next = list2;
25+
list2 = list2.next;
26+
}
27+
temp = temp.next;
28+
}
29+
30+
// list1, list2 중 어떤게 끝까지 갔는지 몰라서 둘 다 체크
31+
// 남은건 그냥 뒤에 가져다가 붙이기
32+
temp.next = list1 || list2;
33+
return answer.next;
34+
};

0 commit comments

Comments
 (0)