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?

Accepted
 
 
Solution:
  使用快慢指针,若两个指针会重合,那么就有环,否则没有
  

 class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == nullptr || head->next == nullptr)return false;
ListNode *slow, *fast;
slow = fast = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (fast == slow)
return true;
}
return false;
}
};

最新文章

  1. WPFTookit Chart 入门
  2. BOM,文档宽高及窗口事件小析
  3. 【小梅哥FPGA进阶学习之旅】基于Altera FPGA 的DDR2+千兆以太网电路设计
  4. BZOJ2862 : 分糖果
  5. java简单的数据库查询(SQLServer数据库)
  6. Windows xp下IDT Hook和GDT的学习
  7. 萌货猫头鹰登录界面动画iOS实现分析
  8. PHP Fatal error问题处理
  9. Python中的引用的使用注意
  10. ObjectiveC1基础代码——类和对象
  11. MapReduce整体架构分析
  12. winform 自定义分页控件 及DataGridview数据绑定
  13. ARP与RARP协议及arp脚本
  14. vue数据请求
  15. FileSaver.js 介绍
  16. 详解EBS接口开发之物料导入API
  17. Python用可变参数找出最大值和最小值
  18. [Swift]LeetCode459. 重复的子字符串 | Repeated Substring Pattern
  19. js身份证正则
  20. 错误 在类中找不到main方法请将main方法定义为 public static void main String args否则JavaFX应用程序类必须扩展javafx-ap

热门文章

  1. 使用iconv提示未知错误
  2. Python笔记(十)_迭代器与生成器
  3. [360前端星计划]BlackJack(21点)(纯JS,附总部学习笔记)
  4. Embedding和Word2Vec实战
  5. Python快速设置Excel表格边框
  6. 通过URL传参数,然后第二个页面需要获取参数
  7. mysql控制台的一些技巧,显示,输入换行,语法正则等
  8. xampp环境下,配置Zend Studio调试php(XDebug) 转摘:http://www.cnblogs.com/tuyithief/archive/2011/06/02/2068431.html
  9. bzoj2521 [Shoi2010]最小生成树
  10. new做了些什么?