Linked List Cycle
2016-07-19 21:30
302 查看
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
/**
* 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) {
ListNode* slow = head;
ListNode* fast = head;
while(fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
return true;
}
return false;
}
};
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
/**
* 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) {
ListNode* slow = head;
ListNode* fast = head;
while(fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
return true;
}
return false;
}
};
相关文章推荐
- 深搜与广搜
- 前端路由&react-router使用姿势
- 【VS开发】【图像处理】ISP图像传感器处理器基础
- HDOJ 1862 EXCEL排序
- 读取excel文件数据,封装成hashmap
- 6. ZigZag Conversion
- Delphi窗体置顶及失去焦点后取得焦点
- 大数据Spark “蘑菇云”行动前传第2课:Scala零基础实战入门的第一堂课及如何成为Scala高手
- Power of Two
- android--checkbox(内部监听器)
- UVA 1587 Box
- servlet+jdbc+sql分页
- python初级项目课(一)
- ANDROID 中常用的第三方框架
- 大型网站架构演化发展历程
- 一笔画问题
- 使用WinSCP完成Windows与Linux之间的文件传输
- python3的模块import操作
- EM算法的一些整理
- Fillder的autoresponder功能