Skip to content

Commit 9ef6846

Browse files
committed
merge-two-sorted-lists solution
1 parent c08fb7c commit 9ef6846

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
13+
/**
14+
time: O(n + m)
15+
space: O(1)
16+
*/
17+
if(list1 == null) return list2;
18+
if(list2 == null) return list1;
19+
20+
ListNode res = new ListNode();
21+
ListNode tmp = res;
22+
23+
while(list1 != null && list2 != null) {
24+
if(list1.val > list2.val) {
25+
tmp.next = list2;
26+
list2 = list2.next;
27+
} else {
28+
tmp.next = list1;
29+
list1 = list1.next;
30+
}
31+
tmp = tmp.next;
32+
}
33+
if(list1 == null) {
34+
tmp.next = list2;
35+
} else {
36+
tmp.next = list1;
37+
}
38+
return res.next;
39+
}
40+
}

0 commit comments

Comments
 (0)