返回环路的开头结点
2015-08-18 22:26
281 查看
给定一个有环链表,实现一个算法返回环路的开头结点。
#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node* next;
}* LinkedListNode;
LinkedListNode FindBeginning(LinkedListNode head)
{
LinkedListNode slow = head;
LinkedListNode fast = head;
//找出碰撞处,将处于链表LOOP_SIZE-k步的位置
while (fast != NULL && fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)//碰撞
{
break;
}
}
//错误检查,没有碰撞处,也即没有环路
if (fast == NULL || fast->next == NULL)
{
return NULL;
}
//将slow指向首部,fast指向碰撞处,两者距离环路起始处k步,
//若两者以相同速度前进,则必定会在环路起始位置碰撞在一起
slow = head;
while (slow != fast)
{
slow = slow->next;
fast = fast->next;
}
//至此两者均指向环路起始处
return fast;
}
相关文章推荐
- zookeeper 用法和日常运维
- LaTeX 代码片插入语法【转】
- ACM经典算法之计算几何
- pat(A)1041. Be Unique(哈希)
- oc NSString/NSArray/NSNumber
- UVA 11426 GCD - Extreme (II) (数论|欧拉函数)
- woj1572 Cyy and Fzz KMP / AC自动机 + DP
- 递归+解析 SRM 593 Division Two - Level Two: WolfDelaymaster
- GoAhead网页提交内容
- hdu 2085 java 核反应堆
- 一些小笔记
- linux总结应用之三 建立内核
- win7下android开发环境的搭建
- MongoDB基本使用
- 老版本AMI的根EBS大小问题
- activeMq笔记
- oc语法04
- Windows编程零基础入门:1.1 Windows是什么?
- ERROR 1064 (HY000): ChildTable multi insert not provided
- BMC IPMI常用命令