题目大意:
给出一个链表,判断其中是否存在环。
算法思想:
利用一个map容器对每个节点做标记,遍历链表中的每个节点,如果该节点做过标记则存在环。
代码如下:
/**
* 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;
ListNode* p=head->next;
map<ListNode*,int> r;
r[head]=1;
while(p){
if(r[p]==1) return true;
r[p]=1;
p=p->next;
}
return false;
}
};