From b92ecfd07fd3523710a65060ce26c84254d8e4d9 Mon Sep 17 00:00:00 2001 From: Koddi-Evangelista Date: Mon, 4 Oct 2021 10:29:40 +0800 Subject: [PATCH 1/2] feat: add algorithm to merge two sorted linked list --- .../Linked-List/MergeTwoSortedLinkedList.js | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Data-Structures/Linked-List/MergeTwoSortedLinkedList.js diff --git a/Data-Structures/Linked-List/MergeTwoSortedLinkedList.js b/Data-Structures/Linked-List/MergeTwoSortedLinkedList.js new file mode 100644 index 0000000000..66b46950e4 --- /dev/null +++ b/Data-Structures/Linked-List/MergeTwoSortedLinkedList.js @@ -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])) +// console.log(mergeTwoLists([], [0])) +// console.log(mergeTwoLists([], [])) +export { mergeTwoSortedLists } From 5f7cc573cf2d36e3b86536a291b5dafb8d444ead Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 6 Oct 2021 13:36:20 +0000 Subject: [PATCH 2/2] Auto-update DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index b78ca59906..c701430ecc 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -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)