|
| 1 | +// Approach 2: |
| 2 | +// ✅ Time Complexity: O(n) |
| 3 | +// ✅ Space Complexity: O(1) |
| 4 | + |
| 5 | +class ListNode { |
| 6 | + val: number; |
| 7 | + next: ListNode | null; |
| 8 | + constructor(val?: number, next?: ListNode | null) { |
| 9 | + this.val = val === undefined ? 0 : val; |
| 10 | + this.next = next === undefined ? null : next; |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +function mergeTwoLists( |
| 15 | + list1: ListNode | null, |
| 16 | + list2: ListNode | null |
| 17 | +): ListNode | null { |
| 18 | + let dummy = new ListNode(0); |
| 19 | + let current = dummy; |
| 20 | + |
| 21 | + while (list1 && list2) { |
| 22 | + if (list1.val <= list2.val) { |
| 23 | + current.next = list1; |
| 24 | + list1 = list1.next; |
| 25 | + } else { |
| 26 | + current.next = list2; |
| 27 | + list2 = list2.next; |
| 28 | + } |
| 29 | + current = current.next; |
| 30 | + } |
| 31 | + |
| 32 | + current.next = list1 || list2; // Attach whatever is left |
| 33 | + |
| 34 | + return dummy.next; |
| 35 | +} |
| 36 | + |
| 37 | + |
| 38 | +// Approach 1: works, but not efficient for big inputs |
| 39 | +// Time Complexity: O(n log n) |
| 40 | +// Space Complexity: O(n) |
| 41 | + |
| 42 | +// function mergeTwoLists( |
| 43 | +// list1: ListNode | null, |
| 44 | +// list2: ListNode | null |
| 45 | +// ): ListNode | null { |
| 46 | +// let stack: number[] = []; |
| 47 | + |
| 48 | +// const dfs = (node: ListNode | null) => { |
| 49 | +// if (!node) { |
| 50 | +// return; |
| 51 | +// } |
| 52 | + |
| 53 | +// stack.push(node.val); |
| 54 | + |
| 55 | +// return dfs(node.next); |
| 56 | +// }; |
| 57 | + |
| 58 | +// dfs(list1); |
| 59 | +// dfs(list2); |
| 60 | + |
| 61 | +// stack.sort((a, b) => a - b); |
| 62 | + |
| 63 | +// if (stack.length === 0) { |
| 64 | +// return null; |
| 65 | +// } |
| 66 | + |
| 67 | +// let merged = new ListNode(); |
| 68 | +// let dummy = merged; |
| 69 | + |
| 70 | +// for (let i = 0; i < stack.length; i++) { |
| 71 | +// dummy.val = stack[i]; |
| 72 | + |
| 73 | +// if (i !== stack.length - 1) { |
| 74 | +// dummy.next = new ListNode(); |
| 75 | +// dummy = dummy.next; |
| 76 | +// } else { |
| 77 | +// dummy.next = null; |
| 78 | +// } |
| 79 | +// } |
| 80 | + |
| 81 | +// return merged; |
| 82 | +// } |
0 commit comments