- 方法一:输出环节点数据
用两个链表指针p,q, 从头节点开始查找。 p一直往后找。p每查找一个节点,q都从头节点一直往后找到q相等的节点,查找过程中如果p的下一个节点刚好是q说明有环。
bool checkCircle2(ListNode* head)
{
if (head == NULL) return false;
ListNode *p = head;
ListNode *q = head->next;
if (q == p) return true;
while (p->next) {
p = p->next;
q = head;
while (q!=p) {
if (q == p->next) {
cout<<"The data of circle Node is "<<p->data<<endl;
return true;
}
q = q->next;
}
}
return 0;
}
bool checkCircle(ListNode *head)
{
if (head == NULL) return false;
Node *p = head;
Node *q = head->next;
while ( q!=NULL) {
if (q == p) return true;
p = p->next;
if (q->next == NULL) return false;
else q = q->next->next;
}
return false;
}