-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path21.merge-two-sorted-lists.js
72 lines (69 loc) · 1.44 KB
/
21.merge-two-sorted-lists.js
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
/*
* @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}
*/
function ListNode(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
let head, resultList;
function addToList(value) {
let newNode = new ListNode(value, null);
if (!resultList) {
head = newNode;
resultList = newNode;
} else {
resultList.next = newNode;
resultList = resultList.next;
}
}
var mergeTwoLists = function (l1, l2) {
head = null;
resultList = null;
let num1, num2;
while (l1 || l2) {
num1 = l1 ? l1.val : -101;
num2 = l2 ? l2.val : -101;
if (num1 < num2) {
if (num1 < -100) {
addToList(num2);
l2 = l2.next;
continue;
}
addToList(num1);
l1 = l1.next;
} else if (num1 > num2) {
if (num2 < -100) {
addToList(num1);
l1 = l1.next;
continue;
}
addToList(num2);
l2 = l2.next;
} else {
addToList(num1);
addToList(num2);
l1 = l1.next;
l2 = l2.next;
}
}
return head;
};
// @lc code=end
// @after-stub-for-debug-begin
module.exports = mergeTwoLists;
// @after-stub-for-debug-end