描述
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;
}
};
本文介绍了一种高效的方法来判断链表中是否存在环路,通过设置快慢指针实现O(n)时间复杂度和O(1)空间复杂度。
373

被折叠的 条评论
为什么被折叠?



