Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head)
{
if(NULL == head)
return false;
ListNode *p = head;
ListNode *q = head;
while(p && q->next)
{
p = p->next;
q = q->next->next;
if(!(p&&q))
return false;
else if(p == q)
return true;
}
return false;
}
};
if(!(p&&q))
return false;
else if(p == q)
return true;
不能换成
if( (p&&q) && (p==q) )
return true;
Last executed input: | {1}, tail connects to node index 0 |