您的位置:首页 > 其它

返回环路的开头结点

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: