Detect circle in linked list

How to detect whether a singly linked list has a circle? If there is a circle, how to determine the beginning of the circle?

C++:
01 Node* begincircle(Node* head)
02 {
03     Node* p=head;
04     Node* q=head;
05     while(true){
06         q=q->next;
07         if(q==NULL)
08             return NULL;
09         q=q->next;
10         if(q==NULL)
11             return NULL;
12         p=p->next;
13         if(p==q){
14             p=head;
15             while(true){
16                 p=p->next;
17                 q=q->next;
18                 if(p==q)
19                     return p;
20             }
21 
22         }
23     }
24 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s