File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ // m: list1, n: list2
2+ // Time complexity: O(m+n)
3+ // Space complexity: O(m+n)
4+
5+ /**
6+ * Definition for singly-linked list.
7+ * function ListNode(val, next) {
8+ * this.val = (val===undefined ? 0 : val)
9+ * this.next = (next===undefined ? null : next)
10+ * }
11+ */
12+ /**
13+ * @param {ListNode } list1
14+ * @param {ListNode } list2
15+ * @return {ListNode }
16+ */
17+ var mergeTwoLists = function ( list1 , list2 ) {
18+ const answer = new ListNode ( ) ;
19+ let current = answer ;
20+
21+ while ( list1 && list2 ) {
22+ if ( list1 . val < list2 . val ) {
23+ current . next = new ListNode ( list1 . val ) ;
24+ list1 = list1 . next ;
25+ } else {
26+ current . next = new ListNode ( list2 . val ) ;
27+ list2 = list2 . next ;
28+ }
29+
30+ current = current . next ;
31+ }
32+
33+ while ( list1 ) {
34+ current . next = new ListNode ( list1 . val ) ;
35+ list1 = list1 . next ;
36+ current = current . next ;
37+ }
38+
39+ while ( list2 ) {
40+ current . next = new ListNode ( list2 . val ) ;
41+ list2 = list2 . next ;
42+ current = current . next ;
43+ }
44+
45+ return answer . next ;
46+ } ;
You can’t perform that action at this time.
0 commit comments