题目
解法一:哈希表
联想到上篇文章相交链表的解法,可以用哈希表存放指针访问过的节点,当再次访问已经访问过的节点时表示是环形链表,返回true退出。
/**
* 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) {
unordered_set<ListNode *>map;
ListNode *p=head;
while(p)
{
if(map.find(p)!=map.end())return true;
else
{
map.insert(p);
p=p->next;
}
}
return false;
}
};
解法二:快慢指针
想象在一个环形跑道上,跑的快的运动员在时间足够下,总会超圈。
这个超圈就是一次相遇,遇到已经访问过的节点。
所以假设快指针fast每次移动两个节点,慢指针每次移动一个节点;只要是环形链表,快指针迟早会再遇到慢指针。这里不禁又浪漫起来了。。
该是你的迟早会遇到。
/**
* 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(head==NULL||head->next==NULL)return false;
ListNode *fast=head->next;
ListNode *slow=head;
while(fast&&fast->next)
{
if(fast==slow)return true;
fast=fast->next->next;
slow=slow->next;
}
return false;
}
};