struct Node
{
int val;
Node *next;
Node(int val_in):val(val_in), next(NULL)
{
}
};
bool hasCircle(Node* head)
{
if(NULL == head)
return false;
Node *fast = head, *slow = head;
while(NULL != fast && NULL != fast->next)//be carefull here
{
fast = fast->next->next;
if(fast == slow)
return true;
else
slow = slow->next;
}
return false;
}
int main()
{
Node* head = NULL;
for(int i = 0; i < 10; ++i)
{
Node* newNode = new Node(i);
newNode->next = head;
head = newNode;
}
cout << hasCircle(head) << endl;
Node* cur = head;
while(NULL != cur->next)
{
//cout << cur->val << endl;
cur = cur->next;
}
cur->next = head->next->next;
cout << hasCircle(head) << endl;
cur = head;
while(NULL != cur->next)
{
cout << cur->val << endl;
cur = cur->next;
}
return 1;
}
判断链表是否有环
最新推荐文章于 2023-11-02 23:16:00 发布