如何判断一个单向链表是否有环路?

来源:互联网 发布:卖家怎么找到淘宝客 编辑:程序博客网 时间:2024/04/29 06:34
struct list{ 
    int data; 
    struct list *next; 
}; 
int has_circle(struct list *head) 

   struct list *cur1 = head; 
   int pos1 = 0; 
   while(cur1)
   { 
      struct list *cur2 = head; 
      int pos2 = 0; 
      pos1 ++; 
      while(cur2)
      { 
          pos2 ++; 
          if(cur2 == cur1)
          { 
             if(pos1 == pos2) 
                 break; 
             else 
                 return 1; //has circle 
          } 
          cur2 = cur2->next; 
       } 
       cur1 = cur1->next; 
   } 
   return 0;