题目:Given a linked list, determine if it has a cycle in it.
解析:可以声明两个指针,一个快指针,一个慢指针,如果链表中存在环,则两个指针肯定会相遇。
代码:
/**
* 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) {
ListNode *fast,*slow;
fast=head;
slow=head;
while(fast!=NULL&&fast->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
return true;
}
return false;
}
};`
【leetcode每日一题】NO141.Linked List Cycle
最新推荐文章于 2024-01-11 13:46:47 发布