[LeetCode] 141. Linked List Cycle 单链表中的环
2024-09-06 09:21:41
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos
which represents the position (0-indexed) in the linked list where tail connects to. If pos
is -1
, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Follow up:
Can you solve it using O(1) (i.e. constant) memory?
这道题是快慢指针的经典应用。只需要设两个指针,一个每次走一步的慢指针和一个每次走两步的快指针,如果链表里有环的话,两个指针最终肯定会相遇。实在是太巧妙了,要是我肯定想不出来。代码如下:
C++ 解法:
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};
Java 解法:
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
}
Github 同步地址:
https://github.com/grandyang/leetcode/issues/141
类似题目:
参考资料:
https://leetcode.com/problems/linked-list-cycle/
https://leetcode.com/problems/linked-list-cycle/discuss/44489/O(1)-Space-Solution
LeetCode All in One 题目讲解汇总(持续更新中...)
最新文章
- Flume_企业中日志处理
- TLD目标跟踪算法
- 【Spring】Junit加载Spring容器作单元测试
- java.util.Date和java.sql.Date的区别和相互转化(转)
- C# 修改IE 源代码参照样例
- POJ 3335 Rotating Scoreboard(半平面交求多边形核)
- jexus asp.net Linux Web Server
- jQuery 黑白插件
- mysql添加超级管理员
- input上传图片(file),预览图片的两种方法。blob与base64编码
- 一文看懂 Github
- Spring Boot 2.x 编写 RESTful API (四) 使用 Mybatis
- python time模块和datetime模块
- 可变有序列表list
- MySQL问题汇总
- L1范数与L2范数​
- 怎样用纯HTML和CSS更改默认的上传文件按钮样式
- zw版【转发·台湾nvp系列Delphi例程】HALCON SmallestRectangle1
- angular ui.router 路由传参数
- winform listbox增加鼠标双击事件
热门文章
- 树莓派4B 更新wiringPi库到2.52的方法的wiringPi库2.5.2版本wiringpi-latest.deb下载
- kali渗透综合靶机(十一)--BSides-Vancouver靶机
- .net core 发布到iis问题 HTTP Error 500.30 - ANCM In-Process Start Failure
- winfrom 获取焦点控件
- ef linq多表查询(三表)
- jmeter返回结果出现乱码
- angular获取时间
- Java生鲜电商平台-源码地址公布与思考和建议
- JDK1.8 Stream
- node整个环境的启动