Linked list Midpoint

I am printing the midpoint but nothing shows

void midPoint(Nodehead) {
Node
fast = head;
Node*slow = head;

while(fast->next != NULL || fast != NULL) {
	fast = fast->next->next;
	slow = slow->next;
}

Node*mid = slow;

cout << "Mid-Point is " << mid->data;

}

The while loop condition must be:
while(fast != NULL && fast->next != NULL)
So change it and then check.

@pratyush63 yes both the condition will true thanks it running fine but the things is when am setting the fast=head it will show nothing but when fast=head->next it will work.

I didn’t get this beacuse while fast reaches to null then it will also run fine

Yes you can dry run this code considering both the cases (for even length linked list and odd length linked list).You will get the mistake.

@pratyush63 yes i dry run this
let suppose we have 1->2->3->4
fast = head
slow = head
then fast will go the 3 element and the slow will 2 then fast = null also the slow 3 so it should return 3
after that condition will false .

You code is running fine. You just have to change the conditions of the while loop to while(fast != NULL && fast->next != NULL)
Previously you had while(fast->next != NULL || fast != NULL)
You can notice here that when fast->next is Null but fast is not null, then the condition will be satisfied and the control will enter the loop. But inside the loop you perform fast = fast->next->next; You know that here fast->next is NULL so this statemnt will turn to fast=NULL->next and this will create the issue.You have to make sure that your code does not perform next of NULL anywhere.

@pratyush63 okays I notice one this it will give we the segment fault when i interchanges both the condition like i did fast->next != NULL && fast !=NULL) why I think we can write both the condition is any order ?

If you first keep fast->next != NULL in the condition this will cause segmentation fault. Consider a case when fast= NULL… so again in the loop condition fast->next is being performed which will give a segmentation fault. So the order must be (fast != NULL && fast->next != NULL
When the first condition is false in case of && ,the second condition is not checked…

@pratyush63 thanku so much.
you clear my all of doubt i better understand the concepts .thanks for putting your great efforts: :slight_smile: