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;
}
};

最新文章

  1. Stanford机器学习笔记-5.神经网络Neural Networks (part two)
  2. 再谈Weiphp公众平台开发——1、成语接龙插件
  3. 20145308刘昊阳 《Java程序设计》第7周学习总结
  4. Python基础:开篇
  5. gcc -l参数和-L参数
  6. POJ 3440 Coin Toss(概率)
  7. java中好玩的案例
  8. sql实现分页
  9. C#取中间文本
  10. POJ1159——Palindrome(最长公共子序列+滚动数组)
  11. jQuery 中的 Ajax $.ajax() load() $.get() $.post() $.getJSON() $.getScript()
  12. 清除delphi 控件DBgrid 的记录
  13. GO语言从入门到放弃目录
  14. 剑指Offer 63. 数据流中的中位数(其他)
  15. mysql视图的作用
  16. day 06 字符串和列表的方法
  17. WAVE文件格式解析
  18. 细说Python2.x与3​​.x版本区别
  19. django 加载静态文件(图片,js,css)
  20. word文档下划线无法显示的解决方法

热门文章

  1. RxSwift 系列(五)
  2. [BZOJ2427][HAOI2010]软件安装(Tarjan+DP)
  3. BeanFactoryPostProcessor和BeanPostProcessor
  4. ACM -- 算法小结(五)字符串算法之Sunday算法
  5. Codeforces Round #300 C. Tourist's Notes 水题
  6. python 用gensim进行文本相似度分析
  7. 查看linux启动的线程信息
  8. Chrome无法播放m3u8格式的直播视频流的问题解决
  9. 搭建简单Ext
  10. WPF性能调试系列 – Ants Performance Profiler