Speed pointer and application "turn"

Source: Internet
Author: User

The speed and speed of the fast pointer refers to the moving step, that is, each moving forward velocity. For example, you can have the fast pointer move forward 2 each time along the linked list, and the slow pointer moves forward 1 times at a time.

determine if a single linked list is a circular link listLet the quick and slow pointer begin to traverse from the list head, the fast pointer moves forward two positions, the slow pointer moves forward one position, and if the fast pointer reaches null, the list ends in null, not the circular list. If the fast pointer catches the slow pointer, it indicates that a loop has occurred. Fast=slow=head;fast=fast->next->next;slow=slow->next;while (True) {if (Fast==null | | fast->next==NULL) Return False;else if (Fast==slow | | fast->next==slow) return true;else{fast=fast->next->next;slow=slow-> Next;}}Finding the median in an ordered listThis method does not use counter variable to realize the function of finding the median. The principle is that the fast pointer moves at twice times the speed of the slow pointer movement, so when the fast pointer reaches the end of the chain, the slow pointer reaches the midpoint. The program also considers the number of nodes in the list of odd even factors, when the fast pointer moves x times to reach the end of the table (1+2X), indicating that the list has an odd number of nodes, directly return the data that the slow pointer points to. If the fast pointer is the second-to-last node, indicating that the number of nodes in the list is even, then you can return half of the upper or lower median or (median + median) according to the rule. while (Fast&&slow)
{
if (fast->next==null)
Return Slow->data;
else if (fast->next!= null && fast->next->next== null)
Return (slow->data + slow->next->data)/2;
Else
{
fast= fast->next;
fast= fast->next;
slow = slow->next;
}
}

Speed pointer and application "turn"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.