Skip to content

Commit ddabf0b

Browse files
committed
Merge Two Sorted Lists
1 parent ec10a0d commit ddabf0b

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// TC: O(n)
2+
// n = length sum of list1 and list2
3+
// SC: O(n)
4+
// n = node 0 ~ length sum of list1 and list2
5+
class Solution {
6+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
7+
ListNode node = new ListNode(0);
8+
ListNode output = node;
9+
10+
while (list1 != null && list2 != null) {
11+
if (list1.val > list2.val) {
12+
node.next = list2;
13+
list2 = list2.next;
14+
} else {
15+
node.next = list1;
16+
list1 = list1.next;
17+
}
18+
node = node.next;
19+
}
20+
21+
if (list1 == null) node.next = list2;
22+
if (list2 == null) node.next = list1;
23+
24+
return output.next;
25+
}
26+
}

0 commit comments

Comments
 (0)