Where does the speed pointer point to exactly?

Source: Internet
Author: User

Where are the fast and fast pointers pointing to? This problem is often not good for people who have just come into contact with this skill. The following will be a single-linked list For example, say a little bit of my personal understanding.


1) A more general wording

if (head = = NULL | | head->next = = NULL) return true; ListNode *fast = head, *slow = head, *prev = null;while (Fast && fast->next) {prev = Slow;slow = slow->next; Fast = Fast->next->next;} </span>

End condition analysis for While loop:

Fast = = NULL even (number of list elements) ******|s***** slow the first element to the second half

Fast->next = = NULL odd *****|s|***** slow point to center position

Sometimes you need to point to the last position of the first part, such as a split list. This requires adding a prev record to the previous element of slow. Is there no need to add prev?

We can deform this method slightly.


2) a slight distortion

if (head = = NULL | | head->next = = NULL) return true; ListNode *fast = head, *slow= head;while (fast->next && fast->next->next) {slow = Slow->next;fast = FAs T->next->next;} </span>
End condition Analysis for While loop:

Fast->next = = NULL Odd ****s|*|*****

Fast->next->next = = NULL even ****s|*****

Slow always points to the last element in the first part.

Compared to the first method, this method detects more than one depth in the while loop, thus ending the loop one step ahead. That is, the slow pointer took a step less.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Where does the speed pointer point to exactly?

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.