判定链表是否有环

 1 #include<iostream>
 2 using namespace std;
 3 
 4 struct ListNode {
 5     int val;
 6     ListNode *next;
 7     ListNode(int x) : val(x), next(nullptr) {}
 8 };
 9 
10 
11 class Solution {
12 public:
13     bool hasCycle(ListNode *head) {
14         if (head == nullptr || head->next == nullptr) {
15             return false;
16         }
17         ListNode *slow = head;
18         ListNode *fast = head->next;
19         while ((fast != nullptr) && (fast->next != nullptr)) {
20             slow = slow->next;
21             fast = fast->next->next;
22             if (slow == fast) {
23                 return true;
24             }
25         }
26         return false;
27     }
28 };
29 
30 
31 int main()
32 {
33     // 1->2->3->4->5->3
34     Solution *s1 = new Solution();
35     ListNode node1(1);
36     ListNode node2(2);
37     ListNode node3(3);
38     ListNode node4(4);
39     ListNode node5(5);
40     node1.next = &node2;
41     node2.next = &node3;
42     node3.next = &node4;
43     node4.next = &node5;
44     node5.next = &node3;
45 
46     std::cout << std::boolalpha;
47     std::cout << "list has cycle:" << s1->hasCycle(&node1) << endl;
48     // 修改节点5指向空,构造无环链表,1->2->3->4->5->nullptr
49     node5.next = nullptr;
50     std::cout << "list has cycle:" << s1->hasCycle(&node1) << endl;
51     // 修改节点5指向节点1,构造有环链表,1->2->3->4->5->1
52     node5.next = &node1;
53     std::cout << "list has cycle:" << s1->hasCycle(&node1) << endl;
54     delete s1;
55     return 0;
56 } 
View Code

运行效果:

 

posted @ 2022-02-21 22:45  跳动的休止符  阅读(11)  评论(0)    收藏  举报