之前看到一道题目,给出一个IP链,如果某个指针指向之前已经指向过的地址,则需要找出这类带环的链,并找出环的入口。以下用C实现代码:
struct Node
{
Node * _next;
int _value;
};
Node* insert(Node * head,Node * n)
{
assert(head);
if (n)
{
n->_next = head->_next;
head->_next = n;
head->_value++;
}
return n;
}
Node * FindCycleLink(Node * head)
{
assert(head);
if (!head)
{
return 0;
}
Node * fast = head;
Node * slow = head;
int pos = 0;
do
{
++pos;
slow = slow->_next;
fast = fast->_next;
if (!fast)
{
break;
}
fast = fast->_next;
}while(fast && slow && fast!=slow);
if (fast!=slow)
{
// no cycle in the link;
return 0;
}
// find the entry of cycle in the link;
fast = head;
while (pos++<=head->_value)
{
slow = slow->_next;
fast = fast->_next;
}
return fast;
}
Node * CreateCycleLink(int len)
{
// Head node;
Node * head = (Node*)malloc(sizeof(Node));
head->_value = 0;// the count of link;
head->_next = 0;
while (len--)
{
Node * n = (Node*)malloc(sizeof(Node));
n->_next = 0;
n->_value = len;
insert(head,n);//insert after head;
}
Node * tail = head;
while (tail->_next)
{
tail = tail->_next;
};
int pos = 10;
Node * cur = head;
while (pos-- && cur)
{
cur = cur->_next;
}
tail->_next = cur; // general the cycle link; at pos = 10;
return head;
}
Node * ClearLink(Node * head)
{
Node * cur = head->_next;
while (head->_value--)
{
head->_next = cur->_next;
delete cur;
cur = head->_next;
}
free(head);
head = 0;
return head;
}
int main()
{
Node * link = CreateCycleLink(24);
Node * cycleentry = FindCycleLink(link);
ClearLink(link);
return 0;
}