LeetCode每日一题 (36) 141. 环形链表(找循环:快慢指针)
程序员文章站
2022-06-18 10:34:39
...
对访问过的节点标记一下:
/**
* 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 false;
while(head->next!=nullptr){
if(head->next->val==100001) return true;
else{
head->val=100001;
head=head->next;
}
}
return false;
}
};
快慢指针:
class Solution {
public:
bool hasCycle(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return false;
}
ListNode* slow = head;
ListNode* fast = head->next;
while (slow != fast) {
if (fast == nullptr || fast->next == nullptr) {
return false;
}
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};
上一篇: 八大排序——快速排序