题目链接: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;
}
}
本文介绍两种检测链表中是否存在环的方法:一种是使用set存储已访问节点,另一种是利用快慢指针技巧。前者时间复杂度为O(N),空间复杂度为O(N);后者时间复杂度同样为O(N),但不使用额外空间。
258

被折叠的 条评论
为什么被折叠?



