class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
bool hasCycle(ListNode *head) {
// write your code here
if(head == NULL || head->next == NULL){return false;}
ListNode *slow = head;
ListNode *fast = head->next;
while(fast != slow){
if(fast == NULL || fast->next == NULL){
return false;
}
fast = fast->next->next;
slow = slow->next;
}
if(fast == slow){return true;}
}
};
注意点:有关带环链表问题,可以使用fast和slow两个指针,设定不同速度,若有环,fast会不断超越slow,一定会有fast=slow。
带环链表
最新推荐文章于 2024-05-09 20:51:13 发布