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
Post a Comment
Thank you! For contacting us we are not available right now you can ask your question we will contact you back soon.