Linked List Cycle II
2014-04-18 21:51
344 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Follow up:
Can you solve it without using extra space?
快慢指针,只要S和F相遇了,我们拿一个从头开始走,一个从相遇的地方开始走
两个都走一步,那么再次相遇必定是环的开始节点!
参考http://www.cnblogs.com/x1957/p/3406448.html
ListNode *detectCycle(ListNode *head)
{
if(head==NULL)
return NULL;
ListNode *slow = head, *fast = head;
while(fast != NULL && fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast)// first meet
{
slow=head;
while(slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;// second meet
}
}
return NULL;
}
null.
Follow up:
Can you solve it without using extra space?
快慢指针,只要S和F相遇了,我们拿一个从头开始走,一个从相遇的地方开始走
两个都走一步,那么再次相遇必定是环的开始节点!
参考http://www.cnblogs.com/x1957/p/3406448.html
ListNode *detectCycle(ListNode *head)
{
if(head==NULL)
return NULL;
ListNode *slow = head, *fast = head;
while(fast != NULL && fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast)// first meet
{
slow=head;
while(slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;// second meet
}
}
return NULL;
}
相关文章推荐
- samba共享文件夹下可读不可写的问题总结
- HTML 中<style>中</style>里面<!-- -->标签是干嘛的
- 制作U盘启动LINUX安装(Ubuntu12.04)
- iOS图片拉伸技巧
- 2011腾讯实习招聘面试题软件开发
- 解决cookie中文乱码问题
- 毕业设计笔记
- My97DatePicker日历实现开始日期小于结束日期验证
- 无线网卡4313GN的Linux驱动下载链接
- Linux块设备驱动程序原理
- Py2.7 no module named tkinter
- loadView、viewDidLoad及viewDidUnload的关系
- mysql5.1.70源码安装详细步骤,支持openssl,支持innodb_plugin存储引擎
- PC机与FL2440的串口通信编程
- mysql备份恢复数据库据/表
- Arduino当avr开发板
- 巴什博弈 杭电 1846
- Source not found for ClassLoader.findBootstrapClass(String) line: not available [native method]
- U盘装WIN7_安装程序无法定位现有分区,也无法创建新的系统分区
- open firefox cookies.sqlite