In this mid point runner technique, why we are taking fast pointer one step ahead of slow pointer instead both the pointers should starts from same position initially?
Mid point Runner technique
@CODER_JATIN you can take as you will both will end by the same results. You will move O(1) already when you take faster ahead
I didn’t understand . . . . .
Hey @CODER_JATIN you have reopened you doubt. So what happens is, your slow as well as fast pointer starts from an initial position. your slow pointer does a jump of 1 step and fast pointer does a jump of 2 steps. So total distance covered by slow pointer is x and fast is 2x so when you do 2x-x you will get x as the mid point of the linked list
ok check this link , https://ide.codingblocks.com/s/409969 , when i input linkedlist as (1 2 3 4) , then it should give output as 3 , but this code is giving output as 2 , why???
It is giving output as 3 only, but it’s wrong. In even length linked list like as you mentioned in case of {1,2,3,4} the mid point is 2 only. if you want to show 3 then don’t do any changes keep it as this only. it will show 3 as an output.
node*middle(node*head)
{
node*fast=head;
node*slow=head;
while(fast!=NULL && fast->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
}
return slow;
}
But if you want to show 2 as the mid point of the linked list then in line number 3 of this code
make it as Node*fast=head->next;
Rest your code works fine for odd length of linked list
jo bhaiya , abhi mera code hai usme agar mai input LINKEDLIST(1 2 3 4) enter karta hu to mid point 2 aa rha hai, to sahi hai vo?
or agar mid point to 3 laana hai to initially fast ko ek steap ahead rakhna pdega i.e node*fast=head->next ???
Yes
yes for even linked list[1,2,3,4] mid point is 2
for odd one both will work that is node*fast=head->next and node *fast=head
There’s a problem on leetcode for the same you can do that too in order to refine this concept.
In that problem if you have linked list of even length like [1,2,3,4] you have to print 3 in it. You can do that by doing this
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.