2.5

Given a circular linked list, implement an algorithm which returns node at the beginning of the loop.
DEFINITION
Circular linked list: A (corrupt) linked list in which a node’s next pointer points to an earlier node, so as to make a loop in the linked list.
EXAMPLE

input: A -> B -> C -> D -> E -> C [the same C as earlier]

output: C

分析:这也是一道链表的经常讨论的题目。有些题目是判断链表中是否有环?方法是使用一个快指针,一个慢指针,两者必定相遇;有些题目是判断链表是否相交,这个的解法就比较多。

我开始确实也没有想明白,研究了一下答案。如果A表示慢指针、B表示快指针,当A到达环入口点的时候,假设B领先A k个位置,则他们相遇的地方一定距离入口点k个位置。因为如果A、B同在起始点,则相遇点也在起始点。B领先k个位置,则相遇点距离起点点反方向k个位置。


代码:

Node* find_loop_start(Node* head){
	if(head==NULL) return;
	Node* fast=head,*slow=head;
	while(1){
		slow=slow->next;
		fast=fast->next;
		if(fast!=NULL){
			fast=fast->next;
			if(fast==slow)
				break;
		}
		else
			break;
	}
	if(fast==NULL)
		return NULL;
	slow=head;
	while(1){
		if(slow==fast)
			return fast;
		slow=slow->next;
		fast=fast->next;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值