当前位置:网站首页>笔试面试题目:判断单链表是否有环
笔试面试题目:判断单链表是否有环
2020-11-08 10:30:00 【osc_ezb5qfcz】
原文发表于:

之前在U公司的笔试中,碰到这样一个问题:
判断单链表是否有环。
首先来看这样一个常识:现实中的环路与单链表的环路,有什么不同呢?
显然:现实中的环路,可以有两个方向,要么循环,要么逃出。然而,在单链表中,指针next只可能有一个指向,所以环路链表必定永远循环,没有出口。如下图所示:

回到问题本身,怎么判断单链表是否有环呢?
算法1:标记法
最容易想到的肯定是标记法。遍历链表时,对访问过的结点做记录。如果是环状单链表,则必然有结点被重复访问。这种思路是非常自然的。
做标记时,可考虑用hash map或者hash set, 需要耗费一些空间。由于思路比较明确,所以就没有必要详细介绍程序了。
算法2:暴力算法
暴力,也是解决问题的一种思路,尽管不一定是最好的方式。
可以这么考虑:一路走到黑,如果到了终点,则没有环,如果没有到达终点,则说明在环中不停绕圈。
我刚才在leetcode上做了一下这个题目,用的是暴力法,能通过所有测试用例,代码如下:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
count := 0
max := 12000
for ; head != nil && count < max; {
count++
head = head.Next
}
if count == max {
return true
}
return false
}
一看就知道,这种暴力算法是有局限性的:比如,如果链表足够长,也会导致count和max相等,可能会误判的。
算法3:快慢指针
摩托车在后,自行车在前,摩托车追赶自行车,如果是一个没有出路的环形路,那么摩托车必然会追上自行车。
所以,我们可以采用类似思路,让快指针在后,慢指针在前,可以判断单链表是否带环。这种方法的好处是,空间复杂度是O(1),且不会出现误判。
既然知道了思路,写程序就是很简单的事情了,故不再赘述。
周末愉快,下周再聊,不见不散。
版权声明
本文为[osc_ezb5qfcz]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4309139/blog/4707995
边栏推荐
- How does spotify drive data-driven decision making?
- 渤海银行百万级罚单不断:李伏安却称治理完善,增速呈下滑趋势
- Test requirements for MIC certification of Bluetooth 2.4G products in Japan
- Oschina plays on Sunday - before that, I always thought I was a
- Improvement of rate limit for laravel8 update
- Japan PSE certification
- 进程、线程和协程的区别
- SQL Server 2008R2 18456错误解决方案
- Which is more worth starting with the difference between vivos7e and vivos7
- 来自不同行业领域的50多个对象检测数据集
猜你喜欢

Game optimization performance (11) - Zhihu

Web novice problem of attacking and defending the world

Close to the double 11, he made up for two months and successfully took the offer from a large factory and transferred to Alibaba

【原创】关于高版本poi autoSizeColumn方法异常的情况

计算机网络基本概念(五)局域网基本原理

数据科学面试应关注的6个要点

ulab 1.0.0发布

Which is more worth starting with the difference between vivos7e and vivos7

Solve Safari browser download file name garbled problem

i5 1135g7和i5 1035g1参数对比区别大吗? 哪个好
随机推荐
【计算机网络】学习笔记,第三篇:数据链路层(谢希仁版)
C++在C的基础上改进了哪些细节
[summary series] technical system of Internet server: high performance database index
学习小结(关于深度学习、视觉和学习体会)
How does spotify drive data-driven decision making?
Flink's sink: a preliminary study
Dogs can also operate drones! You're right, but it's actually an autonomous drone - you know
Mozi college SQL injection solution
What details does C + + improve on the basis of C
Mate 40 series launch with Huawei sports health service to bring healthy digital life
Six key points of data science interview
Unparseable date: 'Mon Aug 15 11:24:39 CST 2016',时间格式转换异常
Application of bidirectional LSTM in outlier detection of time series
Improvement of rate limit for laravel8 update
Rust:命令行参数与环境变量操作
print( 'Hello,NumPy!' )
糟糕,系统又被攻击了
Shiyou's numerical analysis assignment
Can you do it with only six characters?
An error occurred while starting the kernel was successfully resolved