Does a nodelist contain circle?

Source: Internet
Author: User

Algorithm summary:

Determine whether a nodelist contains circle

1. The nodelist has no node, return 0

2. The nodelist has one node and the next field point to NULL return false

3. The nodelist has more than one nodes (at least two nodes)

1) define two point, P1 and P2, initially both point to head of the List;

2) Move P1 one step and P2 two steps each time, if the list has circle, P1 and P2 will point to the same node after several steps.

3) If P2 next field point to null after several steps, it indicates that there is no circle in the list.

Implement code

Code
1 Typedef Int Datatype;
2 Typedef Struct Node {
3 Datatype data;
4 Struct Nodelist * Next;
5 } Nodelist;
6
7 Int Iscircleinlist (nodelist * List ){
8 Linklist * P1 = List;
9 Linklist * P2 = List;
10 While (Node -> Next ! = Null && Node2 -> Next -> Next ! = Null)
11 {
12 P1 = Node -> Next;
13 P2 = Node2 -> Next -> Next;
14 If (P1 = P2) Return   1 ;
15 }
16
17 Return   0 ;
18

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.