当前位置:网站首页>LeetCode 141、环形链表
LeetCode 141、环形链表
2022-04-21 15:31:00 【亡于灬】
141、环形链表
1)题目描述
给你一个链表的头节点 head ,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。
如果链表中存在环 ,则返回 true 。 否则,返回 false 。
示例 1:

输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:

输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:

输入:head = [1], pos = -1
输出:false
解释:链表中没有环。
提示:
- 链表中节点的数目范围是
[0, 10^4] -10^5 <= Node.val <= 10^5pos为-1或者链表中的一个 有效索引 。
2)分析
快慢指针。慢指针从head出发,快指针从head->next出发。
- 提前判断,如果
head或者head->next为空指针,即所给的链表为空链表或者只有一个结点,一定不含环,直接返回false; - 遍历过程中,若
fast指针或者fast->next为空指针,说明到达了链表尾部,不含环,返回false; - 若原本在前面的快指针与慢指针相等,即快指针从后面追上了慢指针,说明含环,返回
true。
3)C++代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head||!head->next)
return false;
ListNode* slow=head;
ListNode* fast=head->next;
while(fast!=slow){
if(!fast||!fast->next)
return false;
slow=slow->next;
fast=fast->next->next;
}
return true;
}
};
版权声明
本文为[亡于灬]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_38342510/article/details/124315991
边栏推荐
- Site intelligent solution
- AcWing 1788. 牛为什么过马路(模拟)
- 企业邮箱怎么登录?企业邮箱登录方法
- 提取CNN模型中间层输出方法
- SQL服务器如何设置起始日期查询语句
- Simple explanation of impermanence loss
- Chapter 7 class
- AcWing 1812. Square pasture (enumeration)
- Easy Language cef3 get request returned source
- ABAQUS loads according to coordinates - analytical field load mapping
猜你喜欢
随机推荐
Smart Park Digital financing - Digital enabling operation management platform solution
读书破万“卷”:国民阅读洞察2022
Loading and unloading of embedded driver module
[binary search - simple] LCP 28 Procurement scheme
企业邮箱如何申请?如何用手机号注册邮箱?
提取CNN模型中间层输出方法
JUC并发学习笔记
华为电力PON配网解决方案
72页互联网智慧园区解决方案
What mailbox do foreign trade companies usually use and how to send e-mail in groups?
AcWing1800. Do not do the last (enumeration)
Machine learning methods create learnable chemical grammars and construct synthetic monomers and polymers
JDBC和数据库连接池
产业园区数字孪生规划方案
With Zhongfu Jinshi's stock speculation, the industry has precipitated for 25 years, and the investment should speak with strength
SMTP协议解读以及如何使用SMTP协议发送电子邮件
sed命令
107页企业数字化转型规划设计
【unity笔记】L3Unity Shader学习开始
[binary search - medium] sword finger offer II 070 Sort numbers that appear only once in the array








