LeetCode:Linked List Cycle
2015-11-26 23:06
197 查看
Linked List Cycle
Total Accepted: 83564 TotalSubmissions: 228287 Difficulty: Medium
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:
使用一个快指针fast和一个慢指针slow,快指针的速度是慢指针的2倍。
如果fast指针能追上慢指针slow,还代表有环存在。
因为两个指针的速度相差1,所以有环的话一定可以追上。
code:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { if(head==NULL) return false; ListNode *fast,*slow; fast=head;slow=head; while(slow && fast && fast->next) { slow=slow->next; fast=fast->next->next; if(fast==slow) return true; } return false; } };
相关文章推荐
- tableView 顶部高出一部分解决方法
- route命令详解与使用实例
- DICOM:DICOM3.0网络通信协议之“开源库实现剖析”
- RGB-YUV转换公式
- 模拟库函数<续>
- Storm:最火的流式处理框架
- 【更改表单元素默认样式】更改文件上传按钮样式
- kafka安装及使用
- 《深入探索C++对象模型》笔记之第一章关于对象
- Add Two Numbers
- HBase编程实例
- Activiti5.13数据库表结构设计
- UITableView tableHeaderView autolayout自动计算高度
- float闭合问题
- 冒泡排序
- XCODE 7 cell的右侧显示不正常
- iOS音频流播放、后台播放、远程控制、锁屏封面等总结
- 【Oracle错误】:ORA-27101 shared memory realm does not exist
- Merge 的小技巧
- 互联网各种免费接口整理