leetcode Linked List Cycle 链表的快慢指针
2014-07-29 15:08
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) {
if(head == NULL)
return false;
ListNode* slow = head;
ListNode* fast = head;
while(fast != NULL) {
fast = fast->next;
if(fast == NULL)
return false;
fast = fast->next;
slow = slow->next;
if(fast == NULL)
return false;
if(slow == fast)
break;
}
return true;
}
};
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* slow = head;
ListNode* fast = head;
while(fast != NULL) {
fast = fast->next;
if(fast == NULL)
return false;
fast = fast->next;
slow = slow->next;
if(fast == NULL)
return false;
if(slow == fast)
break;
}
return true;
}
};
相关文章推荐
- LeetCode:Linked List Cycle--链表快慢指针实现求链表中位和查找链表中是否存在环
- leetcode--Linked List Cycle--判断链表是否有环
- [LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- C实现 LeetCode->Linked List Cycle 双指针大法)(单链表是否有环)
- 【leetcode】【单链表】【142】Linked List Cycle II
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- 【LeetCode-面试算法经典-Java实现】【141-Linked List Cycle(单链表中有环)】
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- 【leetcode】Linked List Cycle II,判断链表是否有环
- [Leetcode-142] Linked List Cycle II(链表有环详细分析)
- LeetCode之“链表”:Linked List Cycle && Linked List Cycle II
- 【leetcode】【单链表】【141】Linked List Cycle
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- Linked List Cycle leetcode II java (寻找链表环的入口)
- LeetCode | Linked List Cycle(判断链表是否有环)
- [LeetCode] Linked List Cycle 单链表中的环
- LeetCode-Linked List Cycle II -有环链表-推理
- Linked List Cycle 有环的链表@LeetCode
- [LeetCode]93. Linked List Cycle II查找链表中环的起始节点
- 【LeetCode-面试算法经典-Java实现】【142-Linked List Cycle II(单链表中有环II)】