判断链表是否有环
来源:互联网 发布:有哪些社交软件 编辑:程序博客网 时间:2024/06/07 05:03
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
bool hasCycle(ListNode *head) {
// write your code here
ListNode *onestep;
ListNode *twosteps;
if (!head)
return false;
onestep = head->next;
if (head->next)
twosteps = head->next->next;
else
return false;
while (onestep && twosteps) {
if (onestep == twosteps)
return true;
onestep = onestep->next;
if (twosteps->next) {
twosteps = twosteps->next->next;
} else {
return false;
}
}
return false;
}
};
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
bool hasCycle(ListNode *head) {
// write your code here
ListNode *onestep;
ListNode *twosteps;
if (!head)
return false;
onestep = head->next;
if (head->next)
twosteps = head->next->next;
else
return false;
while (onestep && twosteps) {
if (onestep == twosteps)
return true;
onestep = onestep->next;
if (twosteps->next) {
twosteps = twosteps->next->next;
} else {
return false;
}
}
return false;
}
};
阅读全文
0 0
- 判断链表是否有环
- 判断链表是否有环
- 如何判断链表是否有环
- 判断链表是否有环
- 判断链表是否有环
- 判断一个链表是否有环
- 单向链表判断是否有环
- 判断链表是否有环
- 判断一个链表是否有环
- 判断链表是否有环
- 算法-判断链表是否有环
- 判断链表是否有环
- 判断一个链表是否有环
- 判断链表是否有环
- 判断循环链表是否有环
- 判断链表是否有环
- 判断链表是否有环
- 判断链表是否有环问题
- Spring Cloud#微服务+Zuul时的跨域问题
- Catch That Cow POJ
- 【c++】传值,传址和传引用
- 3.1.2 WebView和JavaScrip交互大全及Android4.4以后的新特性
- java序列化与反序列化
- 判断链表是否有环
- STL之Vector
- 动态隐藏ALV的行和列
- python中的list实现CRUD操作
- Python函数参数问题
- Java中Synchronized的用法
- 水题生成器
- redis
- 为什么?为什么?为什么WA啊!洛谷 [USACO1.1]贪婪的送礼者{已AC}