Skip to content

Commit 931ef0f

Browse files
committed
feat: solve merge two sorted lists
1 parent cd96d8b commit 931ef0f

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
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+
1. understanding
15+
- merge 2 sorted linked list
16+
2. strategy
17+
- assign return ListNode
18+
- for each node, started in head, compare each node's value, and add smaller value node to return node, and move the node's head to head.next
19+
3. complexity
20+
- time: O(N + M), N is the length of list1, M is the length of list2
21+
- space: O(1), exclude the return variable
22+
*/
23+
ListNode curr = null;
24+
ListNode ret = null;
25+
26+
while (list1 != null && list2 != null) {
27+
if (list1.val < list2.val) {
28+
ListNode node = new ListNode(list1.val);
29+
if (ret == null) {
30+
ret = node;
31+
} else {
32+
curr.next = node;
33+
}
34+
list1 = list1.next;
35+
curr = node;
36+
} else {
37+
ListNode node = new ListNode(list2.val);
38+
if (ret == null) {
39+
ret = node;
40+
} else {
41+
curr.next = node;
42+
}
43+
list2 = list2.next;
44+
curr = node;
45+
}
46+
}
47+
48+
while (list1 != null) {
49+
ListNode node = new ListNode(list1.val);
50+
if (ret == null) {
51+
ret = node;
52+
} else {
53+
curr.next = node;
54+
}
55+
list1 = list1.next;
56+
curr = node;
57+
}
58+
59+
while (list2 != null) {
60+
ListNode node = new ListNode(list2.val);
61+
if (ret == null) {
62+
ret = node;
63+
} else {
64+
curr.next = node;
65+
}
66+
list2 = list2.next;
67+
curr = node;
68+
}
69+
70+
return ret;
71+
}
72+
}
73+

0 commit comments

Comments
 (0)