I am following the below approach to calculate the middle element from the linked list
, but I want is there any built in method or any other approach which can als
The basic algorithm would be
Take two pointers
Make both pointing to first node
Increment first with two nodes and second with one, at a time.
Loop until the 1st loop reaches the end. At this point, the 2nd will be at the middle.
Example:-
while ( p2.next != null ) {
p2 = p2.next;
if (p2.next != null) {
p2 = p2.next;
p1 = p1.next;
}
}
It will definitely work in odd case, for even case you need to check one more condition if first point is allowed to move next but not next to next then both pointers will be at middle you need to decide which to take as middle.