File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for singly-linked list.
3+ * function ListNode(val, next) {
4+ * this.val = (val===undefined ? 0 : val)
5+ * this.next = (next===undefined ? null : next)
6+ * }
7+ */
8+ /**
9+ * @param {ListNode } list1
10+ * @param {ListNode } list2
11+ * @return {ListNode }
12+ */
13+ var mergeTwoLists = function ( list1 , list2 ) {
14+ // Make sure both or one of the list is null
15+ if ( ! list1 && ! list2 ) return null ;
16+ if ( ! list1 ) return list2 ;
17+ if ( ! list2 ) return list1 ;
18+
19+ // Create dummy listNode
20+ let dummy = new ListNode ( 0 ) ;
21+ let head = dummy ;
22+ // Make head of dummy list by using smaller node from list1 and list2
23+ while ( list1 && list2 ) {
24+ if ( list1 . val <= list2 . val ) {
25+ dummy . next = list1 ;
26+ list1 = list1 . next ;
27+ } else {
28+ dummy . next = list2 ;
29+ list2 = list2 . next ;
30+ }
31+ // After choosing with dummy list, head should be moved next
32+ dummy = dummy . next ;
33+ }
34+ // Iterate until both of list head is equal to null
35+ if ( list1 !== null ) {
36+ dummy . next = list1 ;
37+ } else {
38+ dummy . next = list2 ;
39+ }
40+ return head . next ;
41+ } ;
42+
43+ // TC: O(m+n)
44+ // SC: O(1)
You can’t perform that action at this time.
0 commit comments