Finding middlemost node of a linked list in JavaScript


Problem

We are required to write a JavaScript function that takes in the head of a linked list as the first and the only argument.

Our function should return the value stored in the middlemost node of the list. And if there are two middlemost nodes, we should return the second one of them.

For example, if the list is like this:

Input

[4, 6, 8, 9, 1]

Output

const output = 8;

Following is the code:

Example

class Node {
   constructor(data) {
      this.data = data;
      this.next = null;
   };
};
class LinkedList {
   constructor() {
      this.head = null;
      this.size = 0;
   };
};
LinkedList.prototype.add = function(data) {
   const newNode = new Node(data);
   let curr;
      if(this.head === null) {
         this.head = newNode;
      } else {
         curr = this.head;
         while(curr.next) {
            curr = curr.next;
      }
      curr.next = newNode;
   };
      this.size++;
};
const list = new LinkedList();
list.add(4);
list.add(6);
list.add(8);
list.add(9);
list.add(1);
const findMiddle = (head) => {
   let slow = head
   let fast = head
   while(fast && fast.next) {
      slow = slow.next
      fast = fast.next.next
   }
   return slow.data
};
console.log(findMiddle(list.head));

Output

8

Updated on: 23-Apr-2021

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements