查找链表中的循环是否没有两个指针 [英] find whether a loop in a linked list without two pointers

查看:15
本文介绍了查找链表中的循环是否没有两个指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查找链表中是否存在循环.你还有其他方法吗而不是使用快指针和慢指针?

find whether there is a loop in a linked list. Do you have other ways instead of using a quick pointer and a slow pointer?

推荐答案

根据您的情况,有多种方法可以做到这一点.

There are a variety of ways you can do this, depending on your situation.

  1. 当您到达某个节点时,将每个节点添加到某种集合中.遍历列表直到到达末尾或在集合中找到一个节点.

  1. Add each node to a Set of some kind when you reach it. Go through the list until you reach the end or find a node already in the Set.

如果节点中有空闲空间,您可以将每个节点标记为已访问"或未访问",然后遍历列表直到找到已标记的节点.

If you have spare space in the nodes, you can mark each node as "visited" or not and walk the list until you find one you've already marked.

当然,这些都有缺点(如内存使用量高)或无法使用的情况,而双指针方法不使用额外内存,几乎适用于所有地方.

These, of course, all have downsides (like high memory use) or situations where they're not usable, while the two-pointer method doesn't use extra memory and is applicable pretty much everywhere.

这篇关于查找链表中的循环是否没有两个指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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