程序员编程艺术:第九章、闲话链表追赶问题(二)

2014-11-23 22:08:27 · 作者: · 浏览: 10
w)
{
circleNode = fast;
return true;
}
else
return false;
}
//copyright@ KurtWang
//July、2011.05.27。
struct Node
{
int value;
Node * next;
};

//1.先判断带不带环
//判断是否有环,返回bool,如果有环,返回环里的节点
//思路:用两个指针,一个指针步长为1,一个指针步长为2,判断链表是否有环
bool isCircle(Node * head, Node *& circleNode, Node *& lastNode)

{
Node * fast = head->next;
Node * slow = head;
while(fast != slow && fast && slow)
{
if(fast->next != NULL)
fast = fast->next;

if(fast->next == NULL)
lastNode = fast;
if(slow->next == NULL)
lastNode = slow;

fast = fast->next;
slow = slow->next;

}
if(fast == slow && fast &