Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

algorithm: find the middle of linked-list #1096

Merged
merged 5 commits into from
Sep 10, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
27 changes: 0 additions & 27 deletions Data-Structures/Linked-List/MiddleOfLinkedList.js

This file was deleted.

13 changes: 13 additions & 0 deletions Data-Structures/Linked-List/SinglyLinkedList.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,19 @@ class LinkedList {
return removedNode.data
}

// Returns a reference to middle node of linked list
MiddleOfLL () {
10kartik marked this conversation as resolved.
Show resolved Hide resolved
// 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) {
appgurueu marked this conversation as resolved.
Show resolved Hide resolved
fast = fast.next.next
slow = slow.next
}
return slow
}

// make the linkedList Empty
clean () {
this.headNode = null
Expand Down
41 changes: 0 additions & 41 deletions Data-Structures/Linked-List/test/MiddleOfLinkedList.test.js

This file was deleted.

26 changes: 26 additions & 0 deletions Data-Structures/Linked-List/test/SinglyLinkedList.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,32 @@ describe('SinglyLinkedList', () => {
expect(list.size()).toBe(1)
})

it('Middle node of linked list', () => {
const list = new LinkedList()
list.addFirst(1)

let MiddleNodeOfLinkedList = list.MiddleOfLL(list.headNode)
// Middle node for list having single node
expect(MiddleNodeOfLinkedList.data).toEqual(1)
10kartik marked this conversation as resolved.
Show resolved Hide resolved

list.addLast(2)
list.addLast(3)
list.addLast(4)
list.addLast(5)
list.addLast(6)
list.addLast(7)

MiddleNodeOfLinkedList = list.MiddleOfLL(list.headNode)
// Middle node for list having odd number of nodes
expect(MiddleNodeOfLinkedList.data).toEqual(4)

list.addLast(10)

MiddleNodeOfLinkedList = list.MiddleOfLL(list.headNode)
// Middle node for list having even number of nodes
expect(MiddleNodeOfLinkedList.data).toEqual(5)
})

it('Check Iterator', () => {
const list = new LinkedList()

Expand Down