Skip to content

Commit ef7634d

Browse files
committed
feat: FindMiddleNode in a Linked List Algorithm
1 parent 9010481 commit ef7634d

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Problem Statement:
3+
Given a non-empty singly linked list, find the middle node.
4+
If there are two middle nodes, return the second middle node.
5+
6+
Link for the Problem: https://leetcode.com/problems/middle-of-the-linked-list/
7+
*/
8+
9+
class FindMiddleNode {
10+
constructor() {
11+
this.head = null
12+
}
13+
14+
// Method to find and return the middle node of the linked list
15+
findMiddle(head) {
16+
let slow = head
17+
let fast = head
18+
19+
while (fast !== null && fast.next !== null) {
20+
slow = slow.next // Move slow by 1 step
21+
fast = fast.next.next // Move fast by 2 steps
22+
}
23+
24+
return slow // Slow will be at the middle node
25+
}
26+
27+
// Convert list to array for easy checking in test cases
28+
solutionToArray(node) {
29+
const list = []
30+
let currentNode = node
31+
while (currentNode) {
32+
list.push(currentNode.data)
33+
currentNode = currentNode.next
34+
}
35+
36+
return list
37+
}
38+
}
39+
40+
export { FindMiddleNode }
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { FindMiddleNode } from '../FindMiddleNode.js'
2+
import { LinkedList } from '../SinglyLinkedList.js'
3+
4+
describe('FindMiddleNode', () => {
5+
it('Check Middle Node of Linked List', () => {
6+
const list = new LinkedList()
7+
list.addFirst(1)
8+
list.addLast(2)
9+
list.addLast(3)
10+
list.addLast(4)
11+
list.addLast(5)
12+
13+
const findMiddleNode = new FindMiddleNode()
14+
const middleNode = findMiddleNode.findMiddle(list.headNode)
15+
16+
// Convert the node and its following nodes to an array for verification
17+
expect(findMiddleNode.solutionToArray(middleNode)).toEqual([3, 4, 5])
18+
})
19+
20+
it('Check Middle Node for Even Number of Elements', () => {
21+
const list = new LinkedList()
22+
list.addFirst(1)
23+
list.addLast(2)
24+
list.addLast(3)
25+
list.addLast(4)
26+
list.addLast(5)
27+
list.addLast(6)
28+
29+
const findMiddleNode = new FindMiddleNode()
30+
const middleNode = findMiddleNode.findMiddle(list.headNode)
31+
32+
// For even-length lists, the second middle node is returned
33+
expect(findMiddleNode.solutionToArray(middleNode)).toEqual([4, 5, 6])
34+
})
35+
})

0 commit comments

Comments
 (0)