How to find middle element/node of Linked List? || Java Dsa || Linked List || Source Code.


Image source:  https://bit.ly/37jfWKC


Linked List is a dynamic data structure. It consists of nodes connected to each other using the next pointer. Each node of the linked list contains the data part (where the data is stored) and the next part (where the address of the next node is stored).

the head is the first node of the linked list. 


In this article, we'll learn how to find the middle of a Linked list.


Procedure:

            First, declare two variables of type Node named slow and fast respectively.


             Node slow = head ;

             Node fast = head;

            

            Now run loop until value of (fast. next. next) becomes null and updates fast to (fast.next.next) and slow to (slow. next).


      while(fast.next.next != null){

            fast = fast.next.next;

            slow = slow.next;

     }


      Fast will jump twice of slow so when fast reached the end of the list definitely slow will be in the middle of the list.

Print middle:

           System.out.println("Middle of Linked List is: " + slow)


SOURCE CODE:


static void printMiddle(Node head){
Node slow = head ;
Node fast = head;

while (fast .next .next != null){
fast = fast.next.next;
slow = slow.next;
}
System.out.println("Middle of LL is: "+slow.data);
}

            

Hopefully, it'll be helpful for all of you.

If you like the article, then share it with your friends who are also learning dsa.

Also, share your views in the comment section. 

                                                                                                                  (THANKS FOR READING)


Related Hashtags :

#dsapractice  

#dsaproblem 

#datastructures


           

Comments