问题描述 链接到标题
解题思路 链接到标题
使用快慢两个指针,fast
一次移动两个节点,slow
一次移动一个节点,如果链表存在环,那么fast
和slow
一定会有相等的时候,否则fast
会运动到链表末尾。
代码 链接到标题
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *vhead = new ListNode(0, head);
ListNode *fast = vhead, *slow = vhead;
while (fast != nullptr && fast->next != nullptr) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow)
return true;
}
return false;
}
};