Skip to content

feat: FindMiddleNode in a Linked List Algorithm #1701

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
40 changes: 40 additions & 0 deletions Data-Structures/Linked-List/FindMiddleNode.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
Problem Statement:
Given a non-empty singly linked list, find the middle node.
If there are two middle nodes, return the second middle node.

Link for the Problem: https://leetcode.com/problems/middle-of-the-linked-list/
*/

class FindMiddleNode {
constructor() {
this.head = null
}

// Method to find and return the middle node of the linked list
findMiddle(head) {
let slow = head
let fast = head

while (fast !== null && fast.next !== null) {
slow = slow.next // Move slow by 1 step
fast = fast.next.next // Move fast by 2 steps
}

return slow // Slow will be at the middle node
}

// Convert list to array for easy checking in test cases
solutionToArray(node) {
const list = []
let currentNode = node
while (currentNode) {
list.push(currentNode.data)
currentNode = currentNode.next
}

return list
}
}

export { FindMiddleNode }
35 changes: 35 additions & 0 deletions Data-Structures/Linked-List/test/FindMiddleNode.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { FindMiddleNode } from '../FindMiddleNode.js'
import { LinkedList } from '../SinglyLinkedList.js'

describe('FindMiddleNode', () => {
it('Check Middle Node of Linked List', () => {
const list = new LinkedList()
list.addFirst(1)
list.addLast(2)
list.addLast(3)
list.addLast(4)
list.addLast(5)

const findMiddleNode = new FindMiddleNode()
const middleNode = findMiddleNode.findMiddle(list.headNode)

// Convert the node and its following nodes to an array for verification
expect(findMiddleNode.solutionToArray(middleNode)).toEqual([3, 4, 5])
})

it('Check Middle Node for Even Number of Elements', () => {
const list = new LinkedList()
list.addFirst(1)
list.addLast(2)
list.addLast(3)
list.addLast(4)
list.addLast(5)
list.addLast(6)

const findMiddleNode = new FindMiddleNode()
const middleNode = findMiddleNode.findMiddle(list.headNode)

// For even-length lists, the second middle node is returned
expect(findMiddleNode.solutionToArray(middleNode)).toEqual([4, 5, 6])
})
})