您的位置:首页 > 其它

如何判断单链表是否有环,如果有怎么找到进入环的节点

2012-08-16 20:31 316 查看
转载自gaofen100博客园,感谢作者整理!

How can one determine whether a singly linked list has a cycle?

第一种方法是从单链表head开始,每遍历一个,就把那个node放在hashset里,走到下一个的时候,把该node放在hashset里查找,如果有相同的,就表示有环,如果走到单链表最后一个node,在hashset里都没有重复的node,就表示没有环。 这种方法需要O(n)的空间和时间。

第二种方法是设置两个指针指向单链表的head, 然后开始遍历,第一个指针走一步,第二个指针走两步,如果没有环,它们会直接走到底,如果有环,这两个指针一定会相遇。

现在找出环的起始位置:

Cpp代码

/* (Step 1) Find the meeting point. This algorithm moves two pointers at
* different speeds: one moves forward by 1 node, the other by 2. They
* must meet (why? Think about two cars driving on a track—the faster car
* will always pass the slower one!). If the loop starts k nodes after the
* start of the list, they will meet at k nodes from the start of the
* loop. */
n1 = n2 = head;
while (TRUE) {
n1 = n1->next;
n2 = n2->next->next;
if (n1 == n2) {
break;
}
}
// Find the start of the loop.
n1 = head;
while (n1->next != n2->next) {
n1 = n1->next;
n2 = n2->next;
}
Now n2 points to the start of the loop.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐