一开始未看清楚题目条件,以为仅判断是否有循环,于是报错
后面发现问题,但是并没有找到循环首结点的思路于是前去参考标准答案:
解法一:
/**
* 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) {
unordered_set<ListNode *> visited;
while(head!=nullptr){
if(visited.count(head)){
return head;
}
visited.insert(head);
head = head->next;
}
return nullptr;
}
};
原来C++中可以直接调用set,方便了许多,解法一的思路较未简单
关键是:
记录一下如何定义
unordered_set<ListNode *> visited;
解法二:
/**
* 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) {
ListNode* fast = head;
ListNode* slow = head;
while(1){
if(fast == nullptr || fast->next == nullptr) return nullptr;
fast = fast->next->next;
slow = slow->next;
if(fast==slow) break;
}
fast = head;
while(slow != fast){
slow = slow->next;
fast = fast->next;
}
return fast;
}
};