Source: Internet
Author: User

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

Can you solve it without using extra space?

Personal thoughts:

1. Determine whether a linked list has a ring. The standard practice is to take the speed pointer, one step, and two steps. When the fast pointer catches up with the slow pointer, it indicates that there is a ring.

2. Pay attention to several points. 1. The empty node linked list has no loops. 2. The two steps of the fast pointer are also step by step. Check every step.

Code:

` 1 #include <stddef.h> 2  3 struct ListNode 4 { 5     int val; 6     ListNode *next; 7     ListNode(int x) : val(x), next(NULL) {}; 8 }; 9 10 class Solution11 {12 public:13     bool hasCycle(ListNode *head)14     {15         if (!head)16         {17             return false;18         }19 20         ListNode *one = head;21         ListNode *two = head;22 23         while (true)24         {25             two = two->next;26             if (!two)27             {28                 return false;29             }30             if (two == one)31             {32                 return true;33             }34             two = two->next;35             if (!two)36             {37                 return false;38             }39             if (two == one)40             {41                 return true;42             }43             one = one->next;            44         }45     }46 };47 48 int main()49 {50     return 0;51 }`
View code

This method is basically used on the Internet. The main problem is to consider special circumstances and boundary conditions.

Related Keywords:

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.