大家好,我是苏貝,本篇博客带大家刷题,如果你觉得我写的还不错的话,可以给我一个赞👍吗,感谢❤️
目录
1.环形链表

解题
思路:

c
bool hasCycle(struct ListNode *head) {
struct ListNode *slow=head;
struct ListNode *fast=head;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(fast==slow)
return true;
}
return false;
}
拓展:
1
慢指针一次走2步,快指针一次走3步,可以解决上面的题目吗?
可以的,因为它们也只是相差了1步,证明同上
2
慢指针一次走1步,快指针一次走3步,走4步,...n步行吗?下面用慢指针一次走1步,快指针一次走3步来证明


2.环形链表II

思路:

c
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode *slow=head;
struct ListNode *fast=head;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
//1.找到相遇的节点
if(slow==fast)
{
//让meet从相遇节点开始走
struct ListNode *meet=slow;
while(head!=meet)
{
head=head->next;
meet=meet->next;
}
return meet;
}
}
return NULL;
}
好了,那么本篇博客就到此结束了,如果你觉得本篇博客对你有些帮助,可以给个大大的赞👍吗,感谢看到这里,我们下篇博客见❤️