Skip to content

Commit c45004c

Browse files
committed
refactor(mergeTwoLists)
1 parent c2b59a4 commit c45004c

File tree

1 file changed

+14
-34
lines changed

1 file changed

+14
-34
lines changed

merge-two-sorted-lists/evan.js

Lines changed: 14 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -9,42 +9,22 @@ function ListNode(val, next) {
99
* @return {ListNode}
1010
*/
1111
var mergeTwoLists = function (list1, list2) {
12-
if (!list1 && !list2) {
13-
return null;
14-
}
15-
16-
if (!list1 || !list2) {
17-
return [list1, list2].find(Boolean);
18-
}
19-
20-
// firstPointer is a head of list who has the smallest value of node
21-
let [firstPointer, secondPointer] =
22-
list1.val < list2.val ? [list1, list2] : [list2, list1];
23-
const mergedList = firstPointer;
24-
25-
if (firstPointer.next === null) {
26-
firstPointer.next = secondPointer;
27-
return mergedList;
28-
}
29-
30-
while (secondPointer !== null) {
31-
let nextFirstPointer = firstPointer.next;
32-
const nextSecondPointer = secondPointer.next;
33-
34-
while (
35-
firstPointer.next !== null &&
36-
firstPointer.next.val < secondPointer?.val
37-
) {
38-
firstPointer = firstPointer.next;
39-
nextFirstPointer = firstPointer.next;
12+
const dummy = new ListNode();
13+
let current = dummy;
14+
15+
while (list1 !== null && list2 !== null) {
16+
if (list1.val < list2.val) {
17+
current.next = list1;
18+
list1 = list1.next;
19+
} else {
20+
current.next = list2;
21+
list2 = list2.next;
4022
}
4123

42-
firstPointer.next = secondPointer;
43-
firstPointer.next.next = nextFirstPointer;
44-
45-
secondPointer = nextSecondPointer;
46-
firstPointer = firstPointer.next;
24+
current = current.next;
4725
}
4826

49-
return mergedList;
27+
current.next = list1 !== null ? list1 : list2;
28+
29+
return dummy.next;
5030
};

0 commit comments

Comments
 (0)