判断链表是否有环是一个老生长谈的问题了,方法有很多,但是我觉得比较容易理解的还是快慢指
针法。
思路如下:两个人在赛跑,两个人速度不变,如果是沿着没有环的赛道,那一定是跑的快的人先到
终点(也就是指针到达链表尾部),如果有环,那么跑的快的一定会先进入环里,并套圈跑的慢的
人,也就是俩个人一定会相遇。
代码如下:
bool hasCycle(ListNode *head) {
if(head==NULL||head->next==NULL) return false;
ListNode* first=head->next;
ListNode* low=head;
while(first!=low){
if(first==NULL||first->next==NULL) return false;
first=first->next->next;
low=low->next;
}
return true;
}
方法二:使用set集合,set是用来去重的有用道具,其中的count()函数用来判断集合中是否存在某
元素。代码如下
bool hasCycle(ListNode *head) {
set<ListNode*> se;
while (head != nullptr) {
if (se.count(head)) {
return true;
}
se.insert(head);
head = head->next;
}
return false;
}