lintcode 带环链表(102)
2017-02-23 09:04
302 查看
给定一个链表,判断它是否有环。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出 -21->10->4->5, tail connects to node index 1,返回 true
**********************************************************************************************************************************
采用快慢指针的方式,快的先走,若有循环,则快的一定会追上慢的。
/**
* 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
if(head==NULL) return false;
ListNode *slow=head;
ListNode *fast=head;
while(true){
fast=fast->next;
if(fast == NULL)
return false;
if(slow == fast)
return true;
slow=slow->next;
fast=fast->next;
if(fast == NULL)
return false;
}
}
};
您在真实的面试中是否遇到过这个题?
Yes
样例
给出 -21->10->4->5, tail connects to node index 1,返回 true
**********************************************************************************************************************************
采用快慢指针的方式,快的先走,若有循环,则快的一定会追上慢的。
/**
* 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
if(head==NULL) return false;
ListNode *slow=head;
ListNode *fast=head;
while(true){
fast=fast->next;
if(fast == NULL)
return false;
if(slow == fast)
return true;
slow=slow->next;
fast=fast->next;
if(fast == NULL)
return false;
}
}
};
相关文章推荐
- lintcode-102-带环链表
- [LintCode 102] 带环链表(Python)
- lintcode(102)带环链表
- lintcode-带环链表-102
- 带环链表-LintCode
- [LintCode] 带环链表 II Linked List Cycle II
- LintCode 带环链表(快慢指针法)
- lintcode-103-带环链表 II
- *[Lintcode]带环链表 II
- LintCode-带环链表 II
- LintCode 带环链表
- lintcode(103)带环链表 II
- 【LintCode】 Linked List Cycle 带环链表
- LinCode_102_带环链表
- LintCode_103_带环链表 II
- lintcode--带环链表II
- LintCode(103)带环链表 II
- Lintcode链表倒数第n个节点
- 题目:带环链表
- [LintCode] 将二叉查找树转换成双链表 Convert Binary Search Tree to Doubly Linked List