题目链接:力扣
这题首先可以考虑暴力做法,每遍历一个节点就记下来,看能不能遍历到相同节点(hash真好用)。代码如下,算是一种空间换时间
/**
* 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) return false;
unordered_map<ListNode*,int> node;
ListNode* p=head;
while(p->next!=NULL){
if(node.find(p)!=node.end()) return true;
node[p]=1;
p=p->next;
}
return false;
}
};
还可以考虑双指针:定义快慢指针,快指针一次走两个节点,慢指针走一个节点,如果有环的话快指针一定会追上慢指针,而环的长度就是两指针相遇时移动的次数。
/**
* 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) {
int res=0; //环的长度
ListNode *p=head,*q=head;
while(q!=NULL){ //无环情况下的最后一个节点
res++;
p=p->next;
q=q->next;
if(q==NULL) return false;
else q=q->next;
if(p==q){
cout<<res<<endl;
return true;
}
}
return false;
}
};