博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
2.5
阅读量:2382 次
发布时间:2019-05-10

本文共 884 字,大约阅读时间需要 2 分钟。

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;	}}

转载地址:http://dbyab.baihongyu.com/

你可能感兴趣的文章
略论并行处理系统的日志设计
查看>>
开发人员应具备的产品设计意识
查看>>
MSComDlg.CommonDialog服务器不能创建对象错误的解决
查看>>
ArcGIS二次开发之读取遥感图像像素值的做法
查看>>
netcdf源码在windows上的编译
查看>>
慎用VC 6.0
查看>>
游戏杆编程心得
查看>>
周例会的作用
查看>>
字符集研究之多字节字符集和unicode字符集
查看>>
字符集研究之不同字符集的转换方式
查看>>
一个应用程序无法启动错误的解决过程
查看>>
除虫记——有关WindowsAPI文件查找函数的一次压力测试
查看>>
Incredibuild导入key的方式
查看>>
跨平台C++开源代码的两种常用编译方式
查看>>
Eclipse的搜索技巧
查看>>
centos常用命令二
查看>>
通过修改kong属性解决不能获取外网域名的问题
查看>>
Eclipse带命令行参数调试
查看>>
php smtp发送邮件
查看>>
wordpress简代码(短代码、shortcode)
查看>>