Skip to content

Commit

Permalink
feat: FindMiddleNode in a Linked List Algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
BKarthik7 committed Oct 1, 2024
1 parent 9010481 commit ef7634d
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
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])
})
})

0 comments on commit ef7634d

Please sign in to comment.