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


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

Output

4

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.

Example

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

# index.html

<html>
<head>
   <title>Middle Element of Linked List</title>
</head>
<body>
   <h1 style="color: red;">
      Welcome To Tutorials Point
   </h1>
   <script>
      // JavaScript program to find
      // middle of linked list
      var head; // Defining the head pointer
      /* Linked list node */
      class Node {
         constructor(val) {
            this.data = val;
            this.next = 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 &&
            fast_ptr.next != null){
               fast_ptr = fast_ptr.next.next;
               slow_ptr = slow_ptr.next;
            }
            document.write(
               "The middle element is [" + slow_ptr.data + "] <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 */
         new_node.next = 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.data + "->");
            tnode = tnode.next;
         }
         document.write("NULL<br/>");
      }
      for (i = 5; i > 0; --i) {
         push(i);
         printList();
         printMiddle();
      }
   </script>
</body>
</html>

Output

It will produce the following output.

Updated on: 28-Apr-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements