LeetCode141:Linked List Cycle
2015-06-07 17:15
375 查看
“`
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
“
算法的思想很简单,定义两个指针,一个每次前进一步,一个每次前进两步。如果在它们前进到下一个节点为NULL之前它们的值相等,表示能找到环,否则不能,注意需要对输入为空进行判断,以及对链表进行处理时需要对每个指针的next元素进行判断。
runtime:12ms
`/**
* 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 * slow=head;
ListNode * fast=head;
};
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
“
算法的思想很简单,定义两个指针,一个每次前进一步,一个每次前进两步。如果在它们前进到下一个节点为NULL之前它们的值相等,表示能找到环,否则不能,注意需要对输入为空进行判断,以及对链表进行处理时需要对每个指针的next元素进行判断。
runtime:12ms
`/**
* 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 * slow=head;
ListNode * fast=head;
//注意这里需要三个判断条件 while(slow->next!=NULL&&fast->next!=NULL&&fast->next->next!=NULL) { //不要写成slow+1,fast+2了 slow=slow->next; fast=fast->next->next; if(slow==fast) return true; } return false; }
};
相关文章推荐
- java类初始化顺序
- uva 10305 给任务排序
- 分析Autofac如何实现Controller的Ioc(Inversion of Control)
- uefi的c++编程支持new和delete
- leetcode--Spiral Matrix II
- 国王的魔镜
- nfs之限定导出属性实例等
- 《人月神话》和个人的一些想法
- Genymotion 出现无法找到vbox的错误解决方案
- iOS面试题及答案2015.6.7
- Java for LeetCode 199 Binary Tree Right Side View
- hdu 1159 Common Subsequence(最长公共子序列)
- ubuntu 10.04 编译和安装新内核
- eclipse快捷键设置问题
- opengl 绘制实心圆柱体
- Maven2 根据项目生成模版项目,并使用该模板批量创建工程。
- mvn安装本地包
- Looksery Cup 2015 A
- Struts-config.xml配置文件《action-mappings》元素的详解
- C#中Winform程序调用WebService方法