141.leetcode Linked List Cycle(easy)[链表是否有环 快慢指针]
2016-08-05 15:56
567 查看
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题目的意思是判断一个链表是否有环,判断的方法是用快慢两个指针,一个指针每次走两步,一个指针每次走一步,当两个指针相遇时那么存在环。
/**
* 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* p = head,*q = head;
while(p != NULL&&q != NULL)
{
p = p->next;
q = q->next;
if(q != NULL)
q = q->next;
if(p == q && p != NULL)
return true;
}
return false;
}
};
Follow up:
Can you solve it without using extra space?
题目的意思是判断一个链表是否有环,判断的方法是用快慢两个指针,一个指针每次走两步,一个指针每次走一步,当两个指针相遇时那么存在环。
/**
* 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* p = head,*q = head;
while(p != NULL&&q != NULL)
{
p = p->next;
q = q->next;
if(q != NULL)
q = q->next;
if(p == q && p != NULL)
return true;
}
return false;
}
};
相关文章推荐
- 提高PHP代码的性能10条建议
- 多线程程序挂起问题解决
- 去除集合中自定义对象的重复值(对象的成员变量值都相同)
- 解决安装Linux之后没有网卡驱动
- android中用到的资源Color
- Qualcomm DragonBoard 410c Display之DSI浅析
- Android开发资源获取国内代理(转载)
- 排序算法总结(二)归并排序【Merge Sort】
- 按钮的内容靠左边对齐
- codevs 1197 Vigenère密码
- nginx日志中文变成类似\xE9\xA6\x96\xE9\xA1\xB5-\xE6\x8E\xA8\xE8\x8D\x90的东西,治本方案
- 基于Spring+SpringMVC+Mybatis的秒杀系统之Service层(2)
- Github上fork之后如何保持同步(Windows环境)
- C语言实现 螺旋数 方阵
- Pch文件如何配置?
- 软件测试面试
- 基于webkit内核webos系统架构
- 【JAVA】hibernate的缓存、事务相关解读
- 一款应用的UI设计是否合格,该如何判断?
- POJ 1961 字符串 KMP (i-next[i])