JavaScript: How to Find the Middle Element of a Linked List?

JavascriptWeb DevelopmentFront End Technology

In this article, we are going to explore Linked List and how to find the middle element of a linked list in JavaScript.

If there are an even number of elements in the linked list, there will be two middle nodes. We will be only printing the latter element out of both elements.

For Example:

Linked List: 1->2->3->4->5->6-> null



There are two ways to find the middle element from a linked list.

Method I

Traverse the whole list and count the number of nodes. Now traverse the node again till count/2 and return the count/2 i.e. the middle element.

Method II

Traverse the linked list using 2 pointers i.e. slow and fast pointer. Move the slow pointer one node at a time and the fast pointer two nodes at once until the fast pointer points to null. When the fast pointer reaches the end slow pointer will point to the middle element.


In the below example, we are going to find the middle element of the linked list in JavaScript.

# index.html

   <title>Middle Element of Linked List</title>
   <h1 style="color: red;">
      Welcome To Tutorials Point
      // JavaScript program to find
      // middle of linked list
      var head; // Defining the head pointer
      /* Linked list node */
      class Node {
         constructor(val) {
   = val;
   = null;
      /* Function to print middle
      of linked list */
      function printMiddle(){
         var slow_ptr = head;
         var fast_ptr = head;
         if (head != null){
            while (fast_ptr != null &&
   != null){
               fast_ptr =;
               slow_ptr =;
               "The middle element is [" + + "] <br/><br/>"
      /* Inserts a new Node at front of the list. */
      function push(new_data) {
            * 1 & 2: Allocate the Node & Put in the data
         var new_node = new Node(new_data);
         /* 3. Make next of new Node as head */ = head;
         /* 4. Move the head to point to new Node */
         head = new_node;
         * This function prints contents of linked
         list starting from the given node
      function printList() {
         var tnode = head;
         while (tnode != null) {
            document.write( + "->");
            tnode =;
      for (i = 5; i > 0; --i) {


It will produce the following output.

Updated on 28-Apr-2022 12:09:37