File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @description
3+ * brainstorming:
4+ * queue
5+ *
6+ * n: length of list1 + list2
7+ * time complexity: O(n)
8+ * space complexity: O(n)
9+ */
10+ var mergeTwoLists = function ( list1 , list2 ) {
11+ ListNode . prototype . tail = null ;
12+
13+ ListNode . prototype . isLast = function ( ) {
14+ return this . val === 0 && this . next === null ;
15+ } ;
16+
17+ ListNode . prototype . pop = function ( ) {
18+ const value = this . val ;
19+ this . val = this . next ? this . next . val : 0 ;
20+ this . next = this . next ? this . next . next : null ;
21+ return value ;
22+ } ;
23+
24+ ListNode . prototype . push = function ( value ) {
25+ const node = new ListNode ( value ) ;
26+ if ( this . isLast ( ) ) {
27+ this . val = value ;
28+ return ;
29+ }
30+
31+ if ( this . tail === null ) {
32+ this . next = node ;
33+ this . tail = node ;
34+ } else {
35+ this . tail . next = node ;
36+ this . tail = node ;
37+ }
38+ } ;
39+
40+ if ( list1 === null && list2 === null ) return null ;
41+ if ( list1 === null || list2 === null ) return list1 ? list1 : list2 ;
42+
43+ const answer = new ListNode ( ) ;
44+
45+ while ( ! ( list1 . isLast ( ) && list2 . isLast ( ) ) ) {
46+ if ( list1 . isLast ( ) ) {
47+ const value = list2 . pop ( ) ;
48+ answer . push ( value ) ;
49+ continue ;
50+ }
51+ if ( list2 . isLast ( ) ) {
52+ const value = list1 . pop ( ) ;
53+ answer . push ( value ) ;
54+ continue ;
55+ }
56+ if ( list1 . val <= list2 . val ) {
57+ const value = list1 . pop ( ) ;
58+ answer . push ( value ) ;
59+ continue ;
60+ }
61+ if ( list2 . val < list1 . val ) {
62+ const value = list2 . pop ( ) ;
63+ answer . push ( value ) ;
64+ continue ;
65+ }
66+ }
67+
68+ return answer ;
69+ } ;
You can’t perform that action at this time.
0 commit comments