LeetCode 141 Linked List Cycle
2017-09-12 15:51
477 查看
题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题目链接
题意:
给一个链表,判断是否有环,,,要求是不使用额外的空间。
我们可以定义两个不同步速的指针,slow和fast,假如不存在环,那么fast永远不会等于slow,fast步速较快,先一步到达结尾NULL,加入存在环,那么一定存在某一步数,fast赶上了slow,此时slow和fast相同,,,我们可以利用这种方法实现不开额外空间判断环的存在。
代码如下:
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast, *slow;
slow = head;
if (slow == NULL) return false;
fast = slow->next;
while (slow != fast) {
if (fast == NULL || fast->next == NULL) return false;
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题目链接
题意:
给一个链表,判断是否有环,,,要求是不使用额外的空间。
我们可以定义两个不同步速的指针,slow和fast,假如不存在环,那么fast永远不会等于slow,fast步速较快,先一步到达结尾NULL,加入存在环,那么一定存在某一步数,fast赶上了slow,此时slow和fast相同,,,我们可以利用这种方法实现不开额外空间判断环的存在。
代码如下:
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast, *slow;
slow = head;
if (slow == NULL) return false;
fast = slow->next;
while (slow != fast) {
if (fast == NULL || fast->next == NULL) return false;
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};
相关文章推荐
- leetcode note--leetcode 141 Linked List Cycle
- LeetCode 141: Linked List Cycle
- (LeetCode 141/142)Linked List Cycle
- Leetcode 141/142 (链表题) Linked List Cycle && Linked List Cycle II
- leetcode 141 Linked List Cycle C++
- Leetcode 141 Linked List Cycle
- [Leetcode 141] Linked List Cycle
- leetcode 141: Linked List Cycle
- 【leetcode】【141】Linked List Cycle
- Leetcode[141]-Linked List Cycle
- Leetcode 141 Linked List Cycle
- LeetCode 141 Linked List Cycle和142 Linked List Cycle II
- 【leetcode】【141】Linked List Cycle
- 【LeetCode】141 - Linked List Cycle
- 【LeetCode 141】Linked List Cycle(Python)
- leetcode_141_Linked List Cycle
- [leetcode]141 Linked List Cycle
- 【leetcode】【单链表】【141】Linked List Cycle
- [Leetcode]#141 Linked List Cycle
- [LeetCode]题解(python):141-Linked List Cycle