You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
The iterative approach uses a dummy node to build the merged list step by step.
list1: 1 → 2 → 4
list2: 1 → 3 → 4
Step 1: Compare 1 and 1 → pick list1
Result: D → 1
Step 2: Compare 2 and 1 → pick list2
Result: D → 1 → 1
Step 3: Compare 2 and 3 → pick list1
Result: D → 1 → 1 → 2
Step 4: Compare 4 and 3 → pick list2
Result: D → 1 → 1 → 2 → 3
Step 5: Compare 4 and 4 → pick list1
Result: D → 1 → 1 → 2 → 3 → 4
Step 6: Append remaining (4 from list2)
Result: D → 1 → 1 → 2 → 3 → 4 → 4
A more elegant solution using recursion.
1/**
2 * Merge Two Sorted Lists
3 *
4 * Time Complexity: O(n + m)
5 * Space Complexity: O(1) for iterative, O(n + m) for recursive
6 */
7
8class ListNode {
9 int val;
10 ListNode next;
11 ListNode() {}
12 ListNode(int val) { this.val = val; }
13 ListNode(int val, ListNode next) { this.val = val; this.next = next; }
14}
15
16// Iterative Approach
17class Solution {
18 public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
19 // Create dummy node to simplify edge cases
20 ListNode dummy = new ListNode(0);
21 ListNode current = dummy;
22
23 // Compare and link nodes
24 while (list1 != null && list2 != null) {
25 if (list1.val < list2.val) {
26 current.next = list1;
27 list1 = list1.next;
28 } else {
29 current.next = list2;
30 list2 = list2.next;
31 }
32 current = current.next;
33 }
34
35 // Append remaining nodes
36 current.next = list1 != null ? list1 : list2;
37
38 return dummy.next;
39 }
40}
41
42// Recursive Approach
43class Solution2 {
44 public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
45 // Base cases
46 if (list1 == null) return list2;
47 if (list2 == null) return list1;
48
49 // Recursive case
50 if (list1.val < list2.val) {
51 list1.next = mergeTwoLists(list1.next, list2);
52 return list1;
53 } else {
54 list2.next = mergeTwoLists(list1, list2.next);
55 return list2;
56 }
57 }
58}
59