Skip to content

Commit 9cb7c0b

Browse files
committed
merge two sorted lists
1 parent 2922419 commit 9cb7c0b

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+
* Runtime: 0ms
3+
* Time Complexity: O(n)
4+
* - list1.length + list2.length
5+
*
6+
* Memory: 44.28MB
7+
* Space Complexity: O(1)
8+
*
9+
* Approach: 빈 node를 만들고 list1, list2의 현재 값을 비교하여 더 작은 값을 추가
10+
*
11+
*/
12+
class Solution {
13+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
14+
if (list1 == null) return list2;
15+
else if (list2 == null) return list1;
16+
17+
ListNode result = new ListNode();
18+
ListNode currentNode = result;
19+
while (list1 != null && list2 != null) {
20+
if (list1.val > list2.val) {
21+
currentNode.next = list2;
22+
list2 = list2.next;
23+
} else {
24+
currentNode.next = list1;
25+
list1 = list1.next;
26+
}
27+
28+
currentNode = currentNode.next;
29+
}
30+
31+
currentNode.next = list1 != null ? list1 : list2;
32+
return result.next;
33+
}
34+
}

0 commit comments

Comments
 (0)