描述
Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
分析:判断链表是否有环路
最好的方法是时间复杂度O(n),空间复杂度O(1) 的。设置两个指针,一个快一个慢,快
的指针每次走两步, 慢的指针每次走一步, 如果快指针和慢指针相遇, 则说明有环。
class Solution {
public:
bool hasCycle(ListNode *head) {
// 设置两个指针,一个快一个慢
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};