Linked List Cycle
来源:互联网 发布:知乎邮箱不能注册了吗 编辑:程序博客网 时间:2024/06/08 07:09
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(NULL==head) return head;
if(head->next==head) return head;
if(NULL==head->next) return NULL;
ListNode *pfast=head,*pslow=head;
while(pfast&&pfast->next)
{
pfast=pfast->next->next;
pslow=pslow->next;
if(pfast==pslow) break;
}
if(pfast==NULL || pfast->next == NULL) //一定要判断pfast, pfast为空证明没有环;
return NULL;
pfast=head;
while(pfast!=pslow)
{
pslow=pslow->next;
pfast=pfast->next;
}
return pfast;
}
public:
ListNode *detectCycle(ListNode *head) {
if(NULL==head) return head;
if(head->next==head) return head;
if(NULL==head->next) return NULL;
ListNode *pfast=head,*pslow=head;
while(pfast&&pfast->next)
{
pfast=pfast->next->next;
pslow=pslow->next;
if(pfast==pslow) break;
}
if(pfast==NULL || pfast->next == NULL) //一定要判断pfast, pfast为空证明没有环;
return NULL;
pfast=head;
while(pfast!=pslow)
{
pslow=pslow->next;
pfast=pfast->next;
}
return pfast;
}
};
双指针发,关键是要分析,数学推导下, 交叉点到head的距离和相遇点到交叉点的距离相等
下面用set 做比较简单,但是空间上就差了
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(NULL==head) return head;
ListNode *p=head;
set<ListNode*>iset;
int i=0;
while(p)
{
i=iset.size();
iset.insert(p);
if(i==iset.size()) return p;
p=p->next;
}
return NULL ;
}
};
0 0
- leetcode Linked List Cycle & Linked List Cycle ||
- Linked List Cycle II Linked List Cycle
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle II
- [LeetCode]Linked List Cycle
- Linked List Cycle
- LeetCode | Linked List Cycle
- C语言,文件
- Java堆 新生代和老年代
- 正确的三个交棒姿势将决定你是否能赢得创新这场接力赛
- uva 558 Wormholes (Bellman-Ford算法判断负环)
- 单例模式(懒汉式和饿汉式)
- Linked List Cycle
- EM算法
- 一个newCachedThreadPool引发的案例
- HDU 2141二分小解
- MySQL强制修改密码
- Java基础整理篇1-比较字符串是否有重复
- 1626 - Brackets sequence(DP)
- 关于SSH中schema约束配置错误导致
- 你真的很熟分布式和事务吗?