[Leetcode] Linked ring in list Cycle single-linked list

Source: Internet
Author: User

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

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

Beginning to think that this problem only need to pay attention not to use extra space, so wrote a time complexity of O (n^2) brute force search algorithm, as follows:

/** * Dumped, time Limit exceeded*/classSolution { Public:    BOOLHascycle (ListNode *head) {        if(!head | |!head->next)return false; ListNode*pre =Head; ListNode*cur = head->Next;  while(cur) {Pre=Head;  while(Cur->next! = Pre && Pre! =cur) {Pre= pre->Next; }            if(Cur->next = = Pre && pre! = cur)return true; Cur= cur->Next; }        return false; }};

But OJ still do not pass, because time Limit exceeded, or need to reduce the complexity of the O (n), so the Internet search the method of the great God, found that it is very magical. You only need to set two pointers, a slow pointer each step, and a two-step fast pointer, if there is a ring in the chain, two pointers will eventually meet. It was so ingenious, if I could not think of it. The code is as follows:

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

[Leetcode] Linked ring in list Cycle single-linked list

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.