Skip to content

Commit a70a317

Browse files
author
10kartik
committed
Refactor: Added method in singly LL and its tests
1 parent b0ddd37 commit a70a317

File tree

4 files changed

+39
-68
lines changed

4 files changed

+39
-68
lines changed

Data-Structures/Linked-List/MiddleOfLinkedList.js

Lines changed: 0 additions & 27 deletions
This file was deleted.

Data-Structures/Linked-List/SinglyLinkedList.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,19 @@ class LinkedList {
193193
return removedNode.data
194194
}
195195

196+
// Returns a reference to middle node of linked list
197+
MiddleOfLL () {
198+
// If there are two middle nodes, return the second middle node.
199+
let fast = this.headNode
200+
let slow = this.headNode
201+
202+
while (fast != null && fast.next != null) {
203+
fast = fast.next.next
204+
slow = slow.next
205+
}
206+
return slow
207+
}
208+
196209
// make the linkedList Empty
197210
clean () {
198211
this.headNode = null

Data-Structures/Linked-List/test/MiddleOfLinkedList.test.js

Lines changed: 0 additions & 41 deletions
This file was deleted.

Data-Structures/Linked-List/test/SinglyLinkedList.test.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,32 @@ describe('SinglyLinkedList', () => {
164164
expect(list.size()).toBe(1)
165165
})
166166

167+
it('Middle node of linked list', () => {
168+
const list = new LinkedList()
169+
list.addFirst(1)
170+
171+
let MiddleNodeOfLinkedList = list.MiddleOfLL(list.headNode)
172+
// Middle node for list having single node
173+
expect(MiddleNodeOfLinkedList.data).toEqual(1)
174+
175+
list.addLast(2)
176+
list.addLast(3)
177+
list.addLast(4)
178+
list.addLast(5)
179+
list.addLast(6)
180+
list.addLast(7)
181+
182+
MiddleNodeOfLinkedList = list.MiddleOfLL(list.headNode)
183+
// Middle node for list having odd number of nodes
184+
expect(MiddleNodeOfLinkedList.data).toEqual(4)
185+
186+
list.addLast(10)
187+
188+
MiddleNodeOfLinkedList = list.MiddleOfLL(list.headNode)
189+
// Middle node for list having even number of nodes
190+
expect(MiddleNodeOfLinkedList.data).toEqual(5)
191+
})
192+
167193
it('Check Iterator', () => {
168194
const list = new LinkedList()
169195

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy