[LeetCode] 141 - Linked List Cycle
2015-10-03 11:13
429 查看
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) {
ListNode *n1, *n2;
n1 = n2 = head;
while (n1 != nullptr && n2 != nullptr) {
n1 = n1->next;
n2 = n2->next;
if (n2) {
n2 = n2->next;
} else {
return false;
}
if (n2 == n1) {
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) {
ListNode *n1, *n2;
n1 = n2 = head;
while (n1 != nullptr && n2 != nullptr) {
n1 = n1->next;
n2 = n2->next;
if (n2) {
n2 = n2->next;
} else {
return false;
}
if (n2 == n1) {
return true;
}
}
return false;
}
};
相关文章推荐
- Maven实战五
- [经济学原理|政治部分]剩余价值理论
- 数组指针and指针数组
- LeetCode: Regular Expression Matching
- 弱校联萌十一大决战之强力热身 C题
- <线段树>寻找神格
- JAVA环境变量配置
- ZOJ 3349 Special Subsequence
- Spark On YARN内存分配
- 【Cpp】删除字符串空格
- 筹集资金只为那一个梦
- Ext.grid.plugin.RowExpander的简单用法
- Iterator和ListIterator的知识点
- uvalive 3485 - 数值积分
- postMessage安全性问题
- 安卓控件使用系列20:ProgressBar进度条控件的使用方法
- 学好技术只为那一个梦
- const成员函数、inline成员函数、static成员函数中关键字的位置
- AI设计---Robot(v1.0),简单对话的实现
- HDU 2547 无剑无我(水~)