Skip to content

Commit 13adfec

Browse files
add: merge-two sorted lists
1 parent b5b77c2 commit 13adfec

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// 시간복잡도 O(N + M)
2+
class Solution {
3+
4+
public ListNode root = null;
5+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
6+
7+
while(list1 != null || list2 != null) {
8+
int v1 = 9999;
9+
int v2 = 9999;
10+
11+
if(list1 != null) {
12+
v1 = list1.val;
13+
}
14+
15+
if(list2 != null) {
16+
v2 = list2.val;
17+
}
18+
19+
if(v1 < v2) {
20+
addNode(v1);
21+
list1 = list1.next;
22+
} else {
23+
addNode(v2);
24+
list2 = list2.next;
25+
}
26+
}
27+
28+
return root;
29+
}
30+
31+
public void addNode (int val) {
32+
if(root == null) {
33+
root = new ListNode(val);
34+
return;
35+
}
36+
37+
ListNode now = root;
38+
while(now.next != null) {
39+
now = now.next;
40+
}
41+
42+
now.next = new ListNode(val);
43+
}
44+
}

0 commit comments

Comments
 (0)