题目链接:Linked List Cycle
题解:
/*
思路:借助一个set,将访问过的节点存储到set中,如果再次访问到set,则返回true,否则返回false;
Time Complexity:O(N)
Space Complexity:(N)
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <set>
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head)return false;
set<ListNode *>listSet;
while(head){
if(listSet.find(head)!=listSet.end())return true;
else{
listSet.insert(head);
head=head->next;
}
}
return false;
}
};
题目follow up:能否不用额外的空间完成任务,当然也是可以的
思路:借助链表的好帮手,快慢指针。
/**
* 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){
/*
Time Complexity:O(N)
*/
if(!head)return false;
ListNode *fast=head;
ListNode *slow=head;
while(fast->next && fast->next->next){
slow=slow->next;
fast=fast->next->next;
if(slow==fast)return true;
}
return false;
}
}