Given a linked list, determine if it has a cycle in it.
Follow up:Can you solve it without using extra space?
判断一个连表是否有环,而且不使用额外空间=。=
用一快一慢两个指针!
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL)
return false;
ListNode *slow = head;
ListNode *fast = head->next;
while (fast != NULL && fast->next != NULL) {
if (slow == fast) // 有环则一定在head前一个节点相遇,故花费(n-1)的时间
return true;
slow = slow->next;
fast = fast->next->next;
}
return false;
}
};
本文介绍了一种不使用额外空间来判断链表中是否存在环的方法。通过使用快慢指针技术,可以在O(n)时间内完成检测。
1208

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



