如何判断链表是否包含循环? [英] How to determine whether a linked list contains a loop?

查看:19
本文介绍了如何判断链表是否包含循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
在没有两个的链表中查找是否有循环指针
如何确定一个链表是否有一个仅使用两个内存位置的循环.
测试链表是否具有循环

在准备求职面试的过程中,我遇到了以下问题:

During a preparation for a job interview, I encountered the following question:

如何使用 O(1) 的额外空间复杂度来确定(任何类型的)链表是否包含循环?您不能假设循环从第一个节点开始(当然,循环不必包含所有节点).

How can you determine whether a linked list (of any type) contains a loop, using additional space complexity of O(1)? You cannot assume that the loop starts at the first node (and of course, the loop doesn't have to contain all nodes).

我找不到答案,虽然我觉得这很简单...

I couldn't find the answer, though I have the feeling it's quite simple...

推荐答案

简单.维护两个指向列表的指针.在每一步,一个指针前移一个链接,另一个指针前移两个链接.测试它们是否指向同一个元素.如果是这样,你有一个循环.如果没有,请重复直到找到一个循环或到达列表的末尾.

Easy. Maintain two pointers into the list. At each step, advance one pointer by a single link, and advance the other by two links. Test to see if they point to the same element. If so, you have a loop. If not, repeat until you find a loop or you reach the end of the list.

这篇关于如何判断链表是否包含循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆