From 6ad24675454eb30f7d05c9c0587ba3a1a656a384 Mon Sep 17 00:00:00 2001 From: Kartik Kapgate <99239411+10kartik@users.noreply.github.com> Date: Sat, 10 Sep 2022 19:17:50 +0530 Subject: [PATCH] algorithm: find the middle of linked-list (#1096) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Added Middle of linked-list implementation. * Added Middle of LL function and tests * Refactor: Added method in singly LL and its tests * Refactor: Method name and inline test calls * Use `!== null` instead of `!= null` Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com> --- .../Linked-List/SinglyLinkedList.js | 15 +++++++++++- .../Linked-List/test/SinglyLinkedList.test.js | 23 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/Data-Structures/Linked-List/SinglyLinkedList.js b/Data-Structures/Linked-List/SinglyLinkedList.js index f591be13c9..c7a803f53c 100644 --- a/Data-Structures/Linked-List/SinglyLinkedList.js +++ b/Data-Structures/Linked-List/SinglyLinkedList.js @@ -6,7 +6,7 @@ * a singly linked list. */ -// Methods - size, head, addLast, addFirst, addAt, removeFirst, removeLast, remove, removeAt, indexOf, isEmpty, elementAt, get, clean +// Methods - size, head, addLast, addFirst, addAt, removeFirst, removeLast, remove, removeAt, indexOf, isEmpty, elementAt, findMiddle, get, clean class Node { constructor (data) { @@ -193,6 +193,19 @@ class LinkedList { return removedNode.data } + // Returns a reference to middle node of linked list + findMiddle () { + // If there are two middle nodes, return the second middle node. + let fast = this.headNode + let slow = this.headNode + + while (fast !== null && fast.next !== null) { + fast = fast.next.next + slow = slow.next + } + return slow + } + // make the linkedList Empty clean () { this.headNode = null diff --git a/Data-Structures/Linked-List/test/SinglyLinkedList.test.js b/Data-Structures/Linked-List/test/SinglyLinkedList.test.js index 4bfde62c84..bb0124226d 100644 --- a/Data-Structures/Linked-List/test/SinglyLinkedList.test.js +++ b/Data-Structures/Linked-List/test/SinglyLinkedList.test.js @@ -164,6 +164,29 @@ describe('SinglyLinkedList', () => { expect(list.size()).toBe(1) }) + it('Middle node of linked list', () => { + const list = new LinkedList() + list.addFirst(1) + + // Middle node for list having single node + expect(list.findMiddle().data).toEqual(1) + + list.addLast(2) + list.addLast(3) + list.addLast(4) + list.addLast(5) + list.addLast(6) + list.addLast(7) + + // Middle node for list having odd number of nodes + expect(list.findMiddle().data).toEqual(4) + + list.addLast(10) + + // Middle node for list having even number of nodes + expect(list.findMiddle().data).toEqual(5) + }) + it('Check Iterator', () => { const list = new LinkedList()