Leetcode--Linked List Cycle
来源:互联网 发布:刘文典打蒋介石知乎 编辑:程序博客网 时间:2024/06/03 17:29
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
下面是错误的解法:
声明两个指针cur nex ,一个(cur)指向头指针,另一个(nex)遍历直到cur==nex 或 nex==NULL
/** * 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||head->next==NULL) return false; ListNode *cur=head; ListNode *nex=head->next; while(nex!=NULL){ if(cur==nex) return true; nex=nex->next; } return false; }};
Submission Result: Time Limit Exceeded
这个错误用这个图可以解释:程序执行这种情况就是个死循环
Solution:
/** * 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||head->next==NULL) return false; ListNode *fast=head; ListNode *slow=head; while(fast!=NULL&&fast->next!=NULL)//fast->nex有意义的前提是fast不为NULL { slow=slow->next; fast=fast->next->next; if(slow==fast) return true; } return false; }};
0 0
- leetcode Linked List Cycle & Linked List Cycle ||
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- [LeetCode]Linked List Cycle
- LeetCode | Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode: Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode] - Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode]Linked List Cycle
- 【LeetCode】Linked List Cycle
- Linked List Cycle - LeetCode
- 【LeetCode】Linked List Cycle
- Linked List Cycle -- LeetCode
- 图的邻接矩阵存储结构
- windows 10预览版 ISO原版安装镜像文件
- GridLayout向后兼容问题
- hihocode的map字符串匹配问题
- 算法【数学】
- Leetcode--Linked List Cycle
- Git Review提交代码失败的解决方法
- 时钟周期,机器周期
- 浅谈快速傅里叶变换
- android
- Linux - Unix环境高级编程(第三版) 代码编译
- ios中对protocol协议的个人理解(一,对事件的监听)
- CodeForces 233B Non-square Equation
- MYSQL注入语句累积