找链表中的环

       之前看到一道题目,给出一个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;
}

 

   

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值