【力扣hot100题】(024)环形链表
很简单的一题,两种思路都写出来了。
一种是哈希表,最容易想到的一种:
/**
* 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) {
unordered_set<ListNode*> st;
while(head){
if(st.find(head)!=st.end()) return 1;
st.insert(head);
head=head->next;
}
return 0;
}
};
一种是快慢指针:
/**
* 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==nullptr) return 0;
ListNode* slow=head;
ListNode* fast=head;
while(fast!=nullptr&&fast->next!=nullptr){
slow=slow->next;
fast=fast->next->next;
if(slow==fast) return 1;
}
return 0;
}
};