解题思路:
定义一个集合,顺序遍历链表,如果当前节点已经在集合里,说明存在环,返回true;如果不在,把当前节点存入集合中。遍历结束,返回false.
原题:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
AC解,C++代码
/**
* 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;
}
set<ListNode *> visited;
ListNode *p = head;
while(p != NULL) {
if (visited.count(p)) {
return true;
}
visited.insert(p);
p = p->next;
}
return false;
}
};