Skip to content

Commit a657326

Browse files
committed
1. Merge Two Sorted Lists
1 parent 7718d7b commit a657326

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

merge-two-sorted-lists/sunjae95.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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+
};

0 commit comments

Comments
 (0)