Skip to content

Commit 6ad2467

Browse files
10kartikappgurueu
andauthored
algorithm: find the middle of linked-list (#1096)
* 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 <[email protected]>
1 parent 644d7f7 commit 6ad2467

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

Data-Structures/Linked-List/SinglyLinkedList.js

+14-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
* a singly linked list.
77
*/
88

9-
// Methods - size, head, addLast, addFirst, addAt, removeFirst, removeLast, remove, removeAt, indexOf, isEmpty, elementAt, get, clean
9+
// Methods - size, head, addLast, addFirst, addAt, removeFirst, removeLast, remove, removeAt, indexOf, isEmpty, elementAt, findMiddle, get, clean
1010

1111
class Node {
1212
constructor (data) {
@@ -193,6 +193,19 @@ class LinkedList {
193193
return removedNode.data
194194
}
195195

196+
// Returns a reference to middle node of linked list
197+
findMiddle () {
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/SinglyLinkedList.test.js

+23
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,29 @@ 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+
// Middle node for list having single node
172+
expect(list.findMiddle().data).toEqual(1)
173+
174+
list.addLast(2)
175+
list.addLast(3)
176+
list.addLast(4)
177+
list.addLast(5)
178+
list.addLast(6)
179+
list.addLast(7)
180+
181+
// Middle node for list having odd number of nodes
182+
expect(list.findMiddle().data).toEqual(4)
183+
184+
list.addLast(10)
185+
186+
// Middle node for list having even number of nodes
187+
expect(list.findMiddle().data).toEqual(5)
188+
})
189+
167190
it('Check Iterator', () => {
168191
const list = new LinkedList()
169192

0 commit comments

Comments
 (0)