2011-11-01 46 views
0

我想了解C中的链接列表,我有一个程序,计数值为10的节点在一个圆形双重列表中。我可以将龟和兔子算法应用于此程序吗?如果是,那么该怎么办?由于这可以改进使用乌龟和野兔算法

int count(node *current, node *start, int c) 
{ 
    if(current == NULL) 
     return c; 
    if((current->value)==10) 
     c = c + 1; 
    if(current->next == start) 
     return c; 
    return count(current->next, start,c); 
} 

我尝试:

int count(node *start, int c) 
{ 

    node *fast = start; 
    if(start == NULL) 
    return 0; 
    if(!(fast=fast->next)) 
    if((start->roll_no)==10) 
     c = c + 1; 
    if(fast==start) 
     return c; 
    return count(start->next,c); 
} 
+0

是的,你可以。该算法是微不足道的。亲自尝试一下。 – leppie

+0

嗨,leppie,我自己尝试过,但它总是给0作为计数。你能帮我弄清楚我做错了什么吗?编辑后的代码在上面发布。感谢您的帮助,并为此感到抱歉。 – user1017072

回答

0

这是我的C++我的版本,做工精细。

int HasCycle(Node* head) 
{ 
    Node* tr = head; 
    Node* hr = tr; 
    while(1) 
    { 
     if(!hr) 
      return 0; 
     hr = hr->next; 
     if(!hr) 
      return 0; 
     hr = hr->next; 
     tr = tr->next; 
     if(hr == tr) 
      return 1; 
    } 

    return 0; 
}