Skip to content

Commit c97dba2

Browse files
committed
Solution for Merge Two Sorted Lists #224
Fix condition in mergeTwoLists to simplify node comparison logic
1 parent dd62e82 commit c97dba2

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
// TC : O(n)
13+
// SC : O(n)
14+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
15+
// Initialize anonymous head for result
16+
ListNode result = new ListNode(0);
17+
// Initialize cursor to track list
18+
ListNode cursor = result;
19+
20+
// If any list remains
21+
while(list1 != null || list2 != null){
22+
// Choose the smaller node
23+
if(list2 == null
24+
|| (list1 != null && list1.val <= list2.val)){
25+
cursor.next = list1;
26+
list1 = list1.next;
27+
}else{
28+
cursor.next = list2;
29+
list2 = list2.next;
30+
}
31+
//Set the cursor to the next
32+
cursor = cursor.next;
33+
}
34+
35+
// Skip dummy head and return the actual merged list
36+
return result.next;
37+
}
38+
}

0 commit comments

Comments
 (0)