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

类似题目:

Linked List Cycle II

Happy Number

参考资料:

https://leetcode.com/problems/linked-list-cycle/

https://leetcode.com/problems/linked-list-cycle/discuss/44489/O(1)-Space-Solution

LeetCode All in One 题目讲解汇总(持续更新中...)

最新文章

  1. Flume_企业中日志处理
  2. TLD目标跟踪算法
  3. 【Spring】Junit加载Spring容器作单元测试
  4. java.util.Date和java.sql.Date的区别和相互转化(转)
  5. C# 修改IE 源代码参照样例
  6. POJ 3335 Rotating Scoreboard(半平面交求多边形核)
  7. jexus asp.net Linux Web Server
  8. jQuery 黑白插件
  9. mysql添加超级管理员
  10. input上传图片(file),预览图片的两种方法。blob与base64编码
  11. 一文看懂 Github
  12. Spring Boot 2.x 编写 RESTful API (四) 使用 Mybatis
  13. python time模块和datetime模块
  14. 可变有序列表list
  15. MySQL问题汇总
  16. L1范数与L2范数​
  17. 怎样用纯HTML和CSS更改默认的上传文件按钮样式
  18. zw版【转发·台湾nvp系列Delphi例程】HALCON SmallestRectangle1
  19. angular ui.router 路由传参数
  20. winform listbox增加鼠标双击事件

热门文章

  1. 树莓派4B 更新wiringPi库到2.52的方法的wiringPi库2.5.2版本wiringpi-latest.deb下载
  2. kali渗透综合靶机(十一)--BSides-Vancouver靶机
  3. .net core 发布到iis问题 HTTP Error 500.30 - ANCM In-Process Start Failure
  4. winfrom 获取焦点控件
  5. ef linq多表查询(三表)
  6. jmeter返回结果出现乱码
  7. angular获取时间
  8. Java生鲜电商平台-源码地址公布与思考和建议
  9. JDK1.8 Stream
  10. node整个环境的启动