class Solution {
public:
bool hasCycle(ListNode *head) {
set<ListNode*> m_set;
//map1<int>a;
while(head!=NULL)
{
if(m_set.count(head)>0)
{
return true;
}
else
{
m_set.insert(head);
}
head=head->next;
}
return false;
}
};
比较经典,用了set,但是效率不高
bool hasCircle(ListNode*head)
{
if (head == NULL || head->next == NULL)
return false;
ListNode*slow = head;
ListNode*fast = head;
/*
while (fast->next!=NULL)
{
fast = fast->next;
if (fast!=NULL)
fast = fast->next;
slow = slow->next;
if (fast == slow)
return true;
}//这个思路不对,我要判断快指针走2步,是否为空,所以不该在循环体内判断,应该是while条件判断
return false;*/
while (fast->next != NULL&&fast->next->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
if (slow == fast)
{
return true;
}
}
return false;
}
第一次写的时候思路不对,看了答案才觉得,还是思路很重要,知道自己想干什么
if(head==NULL||head->next==NULL)
return false;
ListNode*cur=head;
while(cur!=NULL)
{
if(cur->val==666666)
{
return true;
}
else{
cur->val=666666;
}
cur=cur->next;
}
return false;
这个更狠,擦,老铁666啊