Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
* Linked-List
* [CycleDetection](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Linked-List/CycleDetection.js)
* [DoublyLinkedList](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Linked-List/DoublyLinkedList.js)
* [MergeTwoSortedLinkedList](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Linked-List/MergeTwoSortedLinkedList.js)
* [RotateListRight](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Linked-List/RotateListRight.js)
* [SingleCircularLinkedList](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Linked-List/SingleCircularLinkedList.js.js)
* [SinglyLinkList](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Linked-List/SinglyLinkList.js)
Expand Down
35 changes: 35 additions & 0 deletions Data-Structures/Linked-List/MergeTwoSortedLinkedList.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Problem source and explanation: https://leetcode.com/problems/merge-two-sorted-lists/

/**
* Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/

const mergeTwoSortedLists = (l1, l2) => {
let node = l1
if (!l1) return l2
if (!l2) return l1
while (node.next) {
node = node.next
}
node.next = l2
node = l1
while (node) {
let curr = node
while (curr) {
if (node.val > curr.val) {
;[curr.val, node.val] = [node.val, curr.val]
}
curr = curr.next
}
node = node.next
}
return l1
}

// console.log(mergeTwoLists([1, 2, 4], [1, 3, 4]))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove these test comments and add proper jest tests.

// console.log(mergeTwoLists([], [0]))
// console.log(mergeTwoLists([], []))
export { mergeTwoSortedLists }