LeetCode141 环形链表

给定一个链表,判断链表中是否有环。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

 

快慢指针,一个走两步一个走一步,迟早相遇。注意判断长度为0或1的情况。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         if(!head || !head->next)
13             return false;
14         ListNode* fast, *slow;
15         fast=head;
16         slow=head;
17         while(fast!=nullptr){
18             if(slow)
19                 slow=slow->next;
20             if(fast)
21                 fast=fast->next;
22             if(fast)
23                 fast=fast->next;
24             if(fast==slow && fast!=nullptr)
25                 return true;
26         }
27         return false;
28     }
29 };

 

posted @ 2020-07-28 21:13  __rookie  阅读(66)  评论(0编辑  收藏  举报