leetcode:Linked List Cycle
2014-11-30 11:30
393 查看
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 *fast, *slow;
if (head == NULL || head->next == NULL) {
return false;
}
slow = head;
fast = head->next->next;
while (fast && fast->next) {
if (slow == fast) {
return true;
}
slow = slow->next;
fast = fast->next->next;
}
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 *fast, *slow;
if (head == NULL || head->next == NULL) {
return false;
}
slow = head;
fast = head->next->next;
while (fast && fast->next) {
if (slow == fast) {
return true;
}
slow = slow->next;
fast = fast->next->next;
}
return false;
}
};
相关文章推荐
- LeetCode编程练习 - Linked List Cycle学习心得
- leetcode 141 Linked List Cycle
- LeetCode: Linked List Cycle
- [C++]LeetCode: 73 Linked List Cycle
- 【LeetCode从零单刷】Linked List Cycle I & II
- LeetCode——Linked List Cycle
- 【LeetCode 141】Linked List Cycle(Python)
- LeetCode Linked List Cycle & Linked List Cycle II题解
- 141.leetcode Linked List Cycle(easy)[链表是否有环 快慢指针]
- LeetCode--Linked List Cycle
- leetcode Linked List Cycle & Linked List Cycle ||
- leetcode Linked List Cycle
- [LeetCode] Linked List Cycle
- LeetCode: Linked List Cycle
- [Leetcode][JAVA] Linked List Cycle I && II
- [LeetCode] Linked List Cycle
- Leetcode-Linked List Cycle II
- [Leetcode]Linked List Cycle
- leetcode-141&142 Linked List Cycle I & II
- leetcode-Linked List Cycle