题目连接:Leetcode 142 Linked List Cycle II
解题思路:用set记录遍历过的结点,如果有结点在遍历过程中两次经过,则为环的起点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
set<ListNode*> gra;
while (head != NULL) {
if (gra.count(head)) return head;
gra.insert(head);
head = head->next;
}
return head;
}
};