链表成环不仅仅包括 收尾成环 还可以 中间成环
方法一(快慢指针):
bool hasCycle(ListNode *head) {
if (head == NULL || head->next == NULL)
return false;
ListNode *slow = head;
ListNode *quick = head->next;
while (slow != quick)
{
if(quick == NULL || quick->next == NULL )
return false;
quick = quick->next->next;
slow = slow ->next;
};
return true;
}
空间复杂度:O(1)
时间复杂度:O(n)
方法二(哈希表):
bool hasCycle(ListNode *head) {
set<ListNode*> hash;
ListNode* p = head;
while(p != NULL)
{
if(hash.count(p))
return true;
hash.insert(p);
p = p->next;
}
return false;
}
STL——set:
set.count()函数:如果包含则返回1(unsigned int),否则返回0(unsigned int);