-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path21.merge-two-sorted-lists.js
More file actions
99 lines (81 loc) · 1.82 KB
/
21.merge-two-sorted-lists.js
File metadata and controls
99 lines (81 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* @lc app=leetcode id=21 lang=javascript
*
* [21] Merge Two Sorted Lists
*/
// @lc code=start
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2) {
let head = new ListNode()
let current = head
let p1 = l1, p2 = l2
while (p1 && p2) {
if (p1.val < p2.val) {
current.next = new ListNode(p1.val)
p1 = p1.next
} else {
current.next = new ListNode(p2.val)
p2 = p2.next
}
current = current.next
}
current.next = p1 || p2
return head.next
}
// @lc code=end
function ListNode(val, next) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
function makeChain(vals) {
let head = new ListNode()
current = head
for(let v of vals) {
current.next = new ListNode(v)
current = current.next
}
return head.next
}
function chainToArray(node) {
let array = []
while (node != null) {
array.push(node.val)
node = node.next
}
return array
}
// console.log(chainToArray(mergeTwoLists(
// makeChain([1, 2, 4]),
// makeChain([1, 3, 4]),
// )))
console.log(chainToArray(mergeTwoLists(
makeChain([]),
makeChain([1, 3, 4]),
)))
console.log(chainToArray(mergeTwoLists(
makeChain([1, 2, 4]),
makeChain([]),
)))
console.log(chainToArray(mergeTwoLists(
makeChain([1, 2, 4]),
makeChain([1, 2, 4]),
)))
console.log(chainToArray(mergeTwoLists(
makeChain([]),
makeChain([]),
)))
console.log(chainToArray(mergeTwoLists(
makeChain([1, 1, 1]),
makeChain([1, 1, 1]),
)))