LeetCode Linked List Cycle 解答程序
2024-09-11 11:06:38
Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
错误解法。因为Cycle可能出现在Link的中间的,所以需要检查其中间Nodes。
bool hasCycle(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head == NULL)
return false; ListNode *cur = head;
while(cur != NULL)
{
cur = cur->next;
if(cur == head)
return true;
}
return false;
}
正确解法:
class Solution {
public: bool find(ListNode *head, ListNode *testpNode)
{
ListNode *p = head;
while (p != testpNode->next)
{
if(p == testpNode && p != testpNode->next)
return false;
p = p->next;
}
return true;
} bool hasCycle(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head == NULL)
return false; ListNode *cur = head;
while(cur != NULL)
{
if(find(head, cur))
return true;
cur = cur->next;
}
return false;
}
};
最新文章
- Stanford机器学习笔记-5.神经网络Neural Networks (part two)
- 再谈Weiphp公众平台开发——1、成语接龙插件
- 20145308刘昊阳 《Java程序设计》第7周学习总结
- Python基础:开篇
- gcc -l参数和-L参数
- POJ 3440 Coin Toss(概率)
- java中好玩的案例
- sql实现分页
- C#取中间文本
- POJ1159——Palindrome(最长公共子序列+滚动数组)
- jQuery 中的 Ajax $.ajax() load() $.get() $.post() $.getJSON() $.getScript()
- 清除delphi 控件DBgrid 的记录
- GO语言从入门到放弃目录
- 剑指Offer 63. 数据流中的中位数(其他)
- mysql视图的作用
- day 06 字符串和列表的方法
- WAVE文件格式解析
- 细说Python2.x与3​​.x版本区别
- django 加载静态文件(图片,js,css)
- word文档下划线无法显示的解决方法
热门文章
- RxSwift 系列(五)
- [BZOJ2427][HAOI2010]软件安装(Tarjan+DP)
- BeanFactoryPostProcessor和BeanPostProcessor
- ACM -- 算法小结(五)字符串算法之Sunday算法
- Codeforces Round #300 C. Tourist's Notes 水题
- python 用gensim进行文本相似度分析
- 查看linux启动的线程信息
- Chrome无法播放m3u8格式的直播视频流的问题解决
- 搭建简单Ext
- WPF性能调试系列 – Ants Performance Profiler