File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments