In this post, we will discuss how to find the middle element in linked list in most efficient way.
Implementation Using Java:
public class FindMid {
public static Node<Integer> create() {
Node<Integer> n1=new Node<Integer>(10);
Node<Integer> n2=new Node<Integer>(20);
Node<Integer> n3=new Node<Integer>(30);
Node<Integer> n4=new Node<Integer>(40);
Node<Integer> n5=new Node<Integer>(50);
n1.next=n2;
n2.next=n3;
n3.next=n4;
n4.next=n5;
return n1;
}
public static void print(Node<Integer> head) {
System.out.println("The linked list is"+" ");
while(head!=null)
{
System.out.println(head.data);
head=head.next;
}
}
public static Node<Integer> mid(Node<Integer> head) {
Node<Integer> slow=head;
Node<Integer> fast=head;
while(fast.next!=null && fast.next.next!=null)
{
slow=slow.next;
fast=fast.next.next;
}
return slow;
}
public static void main(String[] args) {
Node<Integer> head=create();
print(head);
Node<Integer> midElement=mid(head);
System.out.println("The mid element is"+" "+midElement.data);
}
}
Happy Coding!
Follow us on Instagram @programmersdoor
Join us on Telegram @programmersdoor
Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.
Follow Programmers Door for more.
Comentários