您的位置:首页 > 其它

单链表是否有环,环的大小,第一个连接点,有环的单链表长度

2016-04-24 20:06 176 查看
给定一个单链表,只给出头指针h:

1、如何判断是否存在环?

2、如何知道环的长度?

3、如何找出环的连接点在哪里?

4、带环链表的长度是多少?

下面是实现,可以相互检查一下是否不正确。

/*
2     Here we discuss four question about single list
3     1. isCircle(ListNode* head)
4     2. lenghtOfCircle_list(ListNode* head)
5     3. firstNodeOfCircle(ListNode* head)
6     4. lengthOfCircle(ListNode* head);
7 */
8 struct ListNode{
9     int val;
10     ListNode* next;
11 };
12 bool isCircle(ListNode* head){
13
14     if(head==NULL)
15         return false;
16     ListNode* slow=head;
17     ListNode* fast=head;
18     while(fast!=NULL){
19         slow=slow->next;
20         if(fast->next!=NULL)
21             fast = fast->next->next;
22         if(slow==fast)
23             return true;
24     }
25     return false;
26 }
27 int lengthOfCircle(ListNode* head){
28     if(head==NULL)
29         return 0;
30     int result=0;
31     ListNode* slow=head;
32     ListNode* fast=head;
33     while(fast!=NULL){
34         slow=slow->next;
35         if(fast->next!=NULL)
36             fast = fast->next->next;
37         if(slow==fast){
38           //conflict node,
39             result++;
40             slow=slow->next;
41             fast=fast->next->next;
42             while(slow!=fast){
43                 slow=slow->next;
44                 fast=fast->next->next;
45                 result++;
46             }
47             return result;
48         }
49     }
50     return result;
51 }
52 ListNode* firstNodeOfCircle(ListNode* head){
53     if(head==NULL)
54         return 0;
55     int result=0;
56     ListNode* slow=head;
57     ListNode* fast=head;
58     while(fast!=NULL){
59         slow=slow->next;
60         if(fast->next!=NULL)
61             fast = fast->next->next;
62         if(slow==fast){
63           //conflict node,
64             while(slow!=head){
65                 slow=slow->next;
66                 head=head->next;
67             }
68             return head;
69         }
70     }
71     return NULL;
72
73 }
74 int lenghtOfCircle_list(ListNode* head){
75     if(head==NULL)
76         return 0;
77     int result=lengthOfCircle(head);
78     if(result==0){
79         //no circle
80         ListNode* node=head;
81         int res=0;
82         while(node!=NULL){
83             node=node->next;
84             ++res;
85         }
86         return res;
87     }
88     ListNode* temp=firstNodeOfCircle(head);
89     ListNode* node=head;
90     int res=0;
91     while(temp!=node){
92         res++;
93         node = node->next;
94     }
95     return res+lengthOfCircle(head);
96 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: