"Leetcode" 141. Linked List Cycle

Source: Internet
Author: User

Title:

Given A linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

Tips:

First, the topic requires ' without using extra space ', which means that the spatial complexity must be controlled within O (1).

Therefore, you can create two variables, point to head at the same time, and then each cycle, so that one of the variables along the linked list forward "walk" two steps, the other "step", so that each cycle after each of their distance will be +1.

If there is a loop in the chain, then this circuit is equivalent to a modulo operation, when the distance between the two is equal to the length of the circuit, it means that has met. So these two variables will eventually meet in a certain step, and this time we can determine the loop.

Conversely, if there is no circuit, then the faster the "walk" of the variable will be the first to go to null, this time can be judged no circuit.

Code:
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public:    BOOLHascycle (ListNode *head) {ListNode*fast =Head; ListNode*slow =Head;  while(Fast && fast->next) {Fast= fast->next->Next; Slow= slow->Next; if(Fast = =slow)return true; }        return false; }};

"Leetcode" 141. Linked List Cycle

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.