0
点赞
收藏
分享

微信扫一扫

环状链表(快慢指针法)

微言记 2022-05-06 阅读 58

 链接:
 https://leetcode-cn.com/problems/linked-list-cycle/description/


//1.刷圈问题,追及问题(快慢指针)--本人方法

bool hasCycle(struct ListNode *head) {

if(head==NULL)//若链表为空,则链表中不可能有环

{

return false;

}



//链表不为空

struct ListNode* fast,*slow;//快慢指针

fast=head;

slow=head;

//判断链表是否第一个就为环

//1.第一个就为环

if(head->next==head)

{

return true;

}

//2.第一个不是环

else

{

fast=fast->next;//快指针先走一步,防止一开始快慢指针就指向同一个节点

}

while(slow!=NULL&NULL&&fast->next!=NULL))

{

if(slow==fast)

{

return true;

}

slow=slow->next;

fast=fast->next->next;

}

return false;

}



//2.答案方法--快慢指针法
/*
解题思路:
定义快慢指针fast,slow, 如果链表确实有环,fast指针一定会在环内追上slow指针。
*/

typedef struct ListNode Node;
bool hasCycle(struct ListNode *head) {
Node* slow = head;
Node* fast = head;

while(fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;

if(slow == fast)
return true;
}

return false;
}
举报

相关推荐

0 条评论