力扣算法——141LinkedListCycel【E】
2024-08-28 23:13:37
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;
}
};
最新文章
- WPFTookit Chart 入门
- BOM,文档宽高及窗口事件小析
- 【小梅哥FPGA进阶学习之旅】基于Altera FPGA 的DDR2+千兆以太网电路设计
- BZOJ2862 : 分糖果
- java简单的数据库查询(SQLServer数据库)
- Windows xp下IDT Hook和GDT的学习
- 萌货猫头鹰登录界面动画iOS实现分析
- PHP Fatal error问题处理
- Python中的引用的使用注意
- ObjectiveC1基础代码——类和对象
- MapReduce整体架构分析
- winform 自定义分页控件 及DataGridview数据绑定
- ARP与RARP协议及arp脚本
- vue数据请求
- FileSaver.js 介绍
- 详解EBS接口开发之物料导入API
- Python用可变参数找出最大值和最小值
- [Swift]LeetCode459. 重复的子字符串 | Repeated Substring Pattern
- js身份证正则
- 错误 在类中找不到main方法请将main方法定义为 public static void main String args否则JavaFX应用程序类必须扩展javafx-ap
热门文章
- 使用iconv提示未知错误
- Python笔记(十)_迭代器与生成器
- [360前端星计划]BlackJack(21点)(纯JS,附总部学习笔记)
- Embedding和Word2Vec实战
- Python快速设置Excel表格边框
- 通过URL传参数,然后第二个页面需要获取参数
- mysql控制台的一些技巧,显示,输入换行,语法正则等
- xampp环境下,配置Zend Studio调试php(XDebug) 转摘:http://www.cnblogs.com/tuyithief/archive/2011/06/02/2068431.html
- bzoj2521 [Shoi2010]最小生成树
- new做了些什么?