Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Jun 29, 2025. It is now read-only.

Commit a81786b

Browse files
Merge pull request #31 from PalmaAnd/0021-merge-two-sorted-lists
0021 merge two sorted lists
2 parents c0f4e57 + 74ac7d5 commit a81786b

File tree

6 files changed

+186
-21
lines changed

6 files changed

+186
-21
lines changed

‎Java/.idea/misc.xml‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Java/.idea/workspace.xml‎

Lines changed: 33 additions & 20 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package problems.leetcode.linked_list;
2+
3+
import problems.leetcode.utils.ListNode;
4+
5+
public class MergeTwoSortedLists {
6+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
7+
ListNode sortedList = new ListNode();
8+
if (list1 == null)
9+
return list2;
10+
if (list2 == null)
11+
return list1;
12+
if (list1.val < list2.val){
13+
sortedList = list1;
14+
list1 = list1.next;
15+
} else {
16+
sortedList = list2;
17+
list2 = list2.next;
18+
}
19+
sortedList.next = mergeTwoLists(list1, list2);
20+
return sortedList;
21+
}
22+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package problems.leetcode.linked_list;
2+
3+
import org.junit.jupiter.api.BeforeEach;
4+
import org.junit.jupiter.api.Test;
5+
import problems.leetcode.utils.ListNode;
6+
7+
import static org.junit.jupiter.api.Assertions.*;
8+
9+
public class MergeTwoSortedListsTest {
10+
11+
private MergeTwoSortedLists solution;
12+
13+
@BeforeEach
14+
public void setUp() {
15+
solution = new MergeTwoSortedLists();
16+
}
17+
18+
@Test
19+
public void testMergeTwoListsBothEmpty() {
20+
ListNode l1 = null;
21+
ListNode l2 = null;
22+
ListNode merged = solution.mergeTwoLists(l1, l2);
23+
assertNull(merged);
24+
}
25+
26+
@Test
27+
public void testMergeTwoListsWithOneEmpty() {
28+
ListNode l1 = new ListNode(1);
29+
ListNode l2 = null;
30+
ListNode merged = solution.mergeTwoLists(l1, l2);
31+
assertEquals(l1, merged);
32+
33+
l1 = null;
34+
l2 = new ListNode(2);
35+
merged = solution.mergeTwoLists(l1, l2);
36+
assertEquals(l2, merged);
37+
}
38+
39+
@Test
40+
public void testMergeTwoListsBothNonEmpty() {
41+
// l1: 1 -> 2 -> 4
42+
ListNode l1 = new ListNode(1);
43+
l1.next = new ListNode(2);
44+
l1.next.next = new ListNode(4);
45+
46+
// l2: 1 -> 3 -> 4
47+
ListNode l2 = new ListNode(1);
48+
l2.next = new ListNode(3);
49+
l2.next.next = new ListNode(4);
50+
51+
// Expected merged list: 1 -> 1 -> 2 -> 3 -> 4 -> 4
52+
ListNode expected = new ListNode(1);
53+
expected.next = new ListNode(1);
54+
expected.next.next = new ListNode(2);
55+
expected.next.next.next = new ListNode(3);
56+
expected.next.next.next.next = new ListNode(4);
57+
expected.next.next.next.next.next = new ListNode(4);
58+
59+
ListNode merged = solution.mergeTwoLists(l1, l2);
60+
assertTrue(areListsEqual(expected, merged));
61+
}
62+
63+
// Helper method to check if two linked lists are equal
64+
private boolean areListsEqual(ListNode l1, ListNode l2) {
65+
while (l1 != null && l2 != null) {
66+
if (l1.val != l2.val) {
67+
return false;
68+
}
69+
l1 = l1.next;
70+
l2 = l2.next;
71+
}
72+
return l1 == null && l2 == null;
73+
}
74+
}
75+

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ Here is a list of the problems I've solved along with links to the corresponding
2828
| [Group Anagrams](https://leetcode.com/problems/group-anagrams/) | [Java](Java/src/main/java/problems/leetcode/arrays_hashing/GroupAnagrams.java) |
2929
| [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [Java](Java/src/main/java/problems/leetcode/arrays_hashing/ProductExceptSelf.java) |
3030
| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [Java](Java/src/main/java/problems/leetcode/arrays_hashing/TopKFrequent.java) |
31+
| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | [Java](Java/src/main/java/problems/leetcode/linked_list/MergeTwoSortedLists.java) |
3132
| [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [Java](Java/src/main/java/problems/leetcode/linked_list/ReverseLinkedList.java) |
3233
| [Daily Temperatures](https://leetcode.com/problems/daily-temperatures/) | [Java](Java/src/main/java/problems/leetcode/stack/DailyTemperatures.java) |
3334
| [Min Stack](https://leetcode.com/problems/min-stack/) | [Java](Java/src/main/java/problems/leetcode/stack/MinStack.java) |
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Merge Two Sorted Lists
2+
3+
## Intuition
4+
5+
When merging two sorted linked lists, my first thought was a recursive approach. The idea is to compare the values of the current nodes in both lists and select the smaller one to be the next node in the merged list and set repace the current node in that list, by the next one. This process continues recursively until one of the input lists is null/empty.
6+
7+
## Approach
8+
9+
1. Create a new `ListNode` called `sortedList` to keep track of the merged list.
10+
2. Check if either of the input lists is empty. If one of them is empty, return the other list because the merged list would be the non-empty list.
11+
3. Compare the values of the current nodes in `list1.val` and `list2.val`.
12+
4. Select the node with the smaller value to be the next node in `sortedList`, and advance the pointer of the corresponding list by setting it to `.next`.
13+
5. Recursively call the `mergeTwoLists` function with the updated lists.
14+
6. Continue this process until either one of `list1` or `list2` are exhausted.
15+
7. Return the `sortedList`, which now contains the merged sorted linked list.
16+
17+
## Complexity
18+
19+
- Time complexity: $$O(n)$$ Where $n$ is the total number of nodes in the two input lists. This is because we visit each node once during the merge process.
20+
- Space complexity: $$O(n)$$ Where $n$ is the space required for the recursive call stack. In the worst case, the stack depth is proportional to the number of nodes in the input lists.
21+
22+
## Code
23+
24+
```java
25+
/**
26+
* Definition for singly-linked list.
27+
* public class ListNode {
28+
* int val;
29+
* ListNode next;
30+
* ListNode() {}
31+
* ListNode(int val) { this.val = val; }
32+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
33+
* }
34+
*/
35+
36+
class Solution {
37+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
38+
ListNode sortedList = new ListNode();
39+
if (list1 == null)
40+
return list2;
41+
if (list2 == null)
42+
return list1;
43+
if (list1.val < list2.val){
44+
sortedList = list1;
45+
list1 = list1.next;
46+
} else {
47+
sortedList = list2;
48+
list2 = list2.next;
49+
}
50+
sortedList.next = mergeTwoLists(list1, list2);
51+
return sortedList;
52+
}
53+
}
54+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /