一、题目说明
题目141. Linked List Cycle,给一个链表,判断是否有环。难度是Easy!
二、我的解答
遍历链表,访问过的打上标记即可。
class Solution{
public:
bool hasCycle(ListNode* head){
while(head!=NULL){
if(head->val == INT_MAX) {
return true;
}
head->val = INT_MAX;
head = head->next;
}
if(head==NULL)return false;
else return true;
}
};
Runtime: 4 ms, faster than 99.89% of C++ online submissions for Linked List Cycle.
Memory Usage: 9.9 MB, less than 50.00% of C++ online submissions for Linked List Cycle.
三、优化措施
快慢指针法,这个不破坏原链表。
class Solution{
public:
bool hasCycle(ListNode* head){
if(head==NULL || head->next==NULL){
return false;
}
ListNode* fast = head->next,*slow = head;
while(fast != slow){
if(fast==NULL || slow==NULL){
return false;
}
slow = slow->next;
fast= fast->next;
if(fast!=NULL) {
fast=fast->next;
}else{
return false;
}
}
return true;
}
};
Runtime: 12 ms, faster than 77.13% of C++ online submissions for Linked List Cycle.
Memory Usage: 9.8 MB, less than 75.00% of C++ online submissions for Linked List Cycle.