-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge-two-sorted-lists.js
More file actions
54 lines (48 loc) · 1.17 KB
/
merge-two-sorted-lists.js
File metadata and controls
54 lines (48 loc) · 1.17 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
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
// https://leetcode.com/problems/merge-two-sorted-lists/
function ListNode(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
var mergeTwoLists = function (list1, list2) {
const list3 = new ListNode();
let prev = list3;
while (list1 !== null && list2 !== null) {
if (list1.val < list2.val) {
prev.next = list1;
list1 = list1.next;
} else {
prev.next = list2;
list2 = list2.next;
}
prev = prev.next;
}
if (list1 === null) {
prev.next = list2;
} else {
prev.next = list1;
}
return list3.next;
};
// create first linked list: 1 -> 3 -> 10
var n3 = new ListNode(10, null);
var n2 = new ListNode(3, n3);
var n1 = new ListNode(1, n2);
var L1 = n1;
// create second linked list: 5 -> 6 -> 9
var n6 = new ListNode(9, null);
var n5 = new ListNode(6, n6);
var n4 = new ListNode(5, n5);
var L2 = n4;
mergeTwoLists(L1, L2);