Linked List Cycle

3020阅读 0评论2015-08-17 qinchaowhut
分类:C/C++


  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  * int val;
  5.  * struct ListNode *next;
  6.  * };
  7.  */

  8. bool hasCycle(struct ListNode *head) {

  9.     struct ListNode* p=head;
  10.     struct ListNode* q=head;
  11.     while((q!=NULL)&&(q->next!=NULL))
  12.     {
  13.         p=p->next;
  14.         q=q->next;
  15.         q=q->next;
  16.         if(p==q)
  17.             return true;
  18.     }
  19.     return false;
  20. }

上一篇:Single Number III
下一篇:Reverse Bits