Interview question speed linked list and speed pointer
- 2020-05-24 05:55:35
- OfStack
Tencent 1 interview question: how to quickly find the location of the length of a single linked list of intermediate nodes? The normal method is to go through it first and find the middle node of 2/length from scratch. The algorithm complexity is: O(3*n/2). The faster way is to use the principle of fast and slow Pointers.
Fast and slow linked list: using the idea of ruler, set two Pointers (1 fast and 1 slow) *serach and *mid, both pointing to the head node of the single linked list at the beginning. But the *search pointer moves twice as fast as *mid. When *search gets to the tail, mid gets right in the middle. The algorithm complexity is: O(n/2)
int GetMidNode(LinkList *L,int elem){
LinkList *search,*mid;
mid = search = L; // Point to the head
while (search->next != NULL){ // When the next node exists
if (search->next->next!=NULL) {// Check if the next node of the next is empty
search = search->next->next;
mid = mid->next;
}
else
search = search->next;
}
elem = mid->data;
return elem;
}
Thank you for reading, I hope to help you, thank you for your support of this site!