给定一个链表,判断它是否有环。
样例
样例 1:
输入: 21->10->4->5, then tail connects to node index 1(value 10).
输出: true
样例 2:
输入: 21->10->4->5->null
输出: false
挑战
不要使用额外的空间
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
bool hasCycle(ListNode * head) {
// write your code here
if(head==NULL) return false;
set<ListNode*> temp;
while(head!=NULL&&!temp.count(head))
{
temp.insert(head);
head=head->next;
}
if(head)return true;
return false;
}
};