Linked List Cycle II
2016-07-19 21:36
190 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Note: Do not modify the linked list.
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:
ListNode *detectCycle(ListNode *head) {
if(head==NULL) return head;
ListNode* slow=head;
ListNode* fast=head;
while(fast!=NULL && fast->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
break;
}
if(fast==NULL || fast->next==NULL) return NULL;
slow=head;
while(slow!=fast)
{
slow=slow->next;
fast=fast->next;
}
return fast;
}
};
null.
Note: Do not modify the linked list.
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:
ListNode *detectCycle(ListNode *head) {
if(head==NULL) return head;
ListNode* slow=head;
ListNode* fast=head;
while(fast!=NULL && fast->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
break;
}
if(fast==NULL || fast->next==NULL) return NULL;
slow=head;
while(slow!=fast)
{
slow=slow->next;
fast=fast->next;
}
return fast;
}
};
相关文章推荐
- Java解决java.io.FileNotFoundException: E:\work\work (拒绝访问。)
- 再谈图的存储方式(邻接矩阵,邻接表,前向星)
- hd1084 What Is Your Grade?
- HDOJ 1872 稳定排序
- highcharts
- Android中常用的优秀开源框架
- 浏览器兼容性处理要点
- 五子棋
- HDU5724 Chess
- Windows下两个python版本怎么分别安装库
- Android百度地图(四)如何引入离线地图包
- pdo 连库
- 英语写作
- 新的开始
- Ol3中Map事件全解析
- C++函数中的那些坑
- c++父类和子类转化致命的代码错误
- 算法导论(5) 二叉搜索树
- 不同的域名指向同一个主机上的不同项目
- CSS的内联和块元素