Skip to content

Commit af050a4

Browse files
committed
solve merge-two-sorted-lists
1 parent f978922 commit af050a4

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

merge-two-sorted-lists/1lsang.ts

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* val: number
5+
* next: ListNode | null
6+
* constructor(val?: number, next?: ListNode | null) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
* }
11+
*/
12+
13+
class ListNode {
14+
val: number
15+
next: ListNode | null
16+
constructor(val?: number, next?: ListNode | null) {
17+
this.val = (val===undefined ? 0 : val)
18+
this.next = (next===undefined ? null : next)
19+
}
20+
}
21+
22+
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
23+
// list1과 list2의 val을 비교해나가면서 새로운 list 생성
24+
// 1. list1 없으면 list2 return
25+
if (!list1) return list2;
26+
// 2. list2 없으면 list1 return
27+
if (!list2) return list1;
28+
29+
const list = new ListNode(-101);
30+
31+
let listNode = list;
32+
let listNode1: ListNode | null = list1;
33+
let listNode2: ListNode | null = list2;
34+
35+
while (listNode1 && listNode2) {
36+
if (listNode1.val > listNode2.val) {
37+
listNode.next = new ListNode(listNode2.val, null);
38+
listNode2 = listNode2.next;
39+
}
40+
else {
41+
listNode.next = new ListNode(listNode1.val, null);
42+
listNode1 = listNode1.next;
43+
}
44+
listNode = listNode.next;
45+
}
46+
if (!listNode1) {
47+
listNode.next = listNode2;
48+
}
49+
else if (!listNode2) {
50+
listNode.next = listNode1;
51+
}
52+
53+
return list.next;
54+
};

0 commit comments

Comments
 (0)