141. Linked List Cycle

来源:互联网 发布:鲁滨逊漂流记java 编辑:程序博客网 时间:2024/05/17 12:03

Given a linked list, determine if it has a cycle in it.

class Solution 

{
public:
    bool hasCycle(ListNode *head) 
    {

         ListNode* p=head;

         ListNode* q=head;

        while(q!=NULL&&q->next!=NULL)

         {

              p=p->next;

              q=q->next->next;

              if(p==q)

               return true;

         }

            return false;

   }

};

原创粉丝点击