leetcode No141. Linked List Cycle

来源:互联网 发布:网络机顶盒安装app 编辑:程序博客网 时间:2024/05/24 00:43

Question

Given a linked list, determine if it has a cycle in it.
判断链表是否有环

Algorithm

用两个指针,一快一慢,如果它们会在某一个地方相遇则证明有环

Accepted Code

class Solution {public:    bool hasCycle(ListNode *head) {        if(head==NULL || head->next==NULL)            return false;        ListNode *slow=head;        ListNode *fast=head;        while(fast!=NULL && fast->next!=NULL)        {            fast=fast->next->next;            slow=slow->next;            if(slow==fast)                return true;        }        return false;    }};
0 0