LEETCODE--Linked List Cycle
2017-02-28 11:52
281 查看
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
判断链表是否有环:使用追赶的方法,设定两个指针slow、fast,从头指针开始,每次分别前进1步、2步。如存在环,则两者相遇;如不存在环,fast遇到NULL退出。
/**
* 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 *slow = head;
ListNode *fast = head;
while(head){
if(fast->next && fast->next->next){
fast = fast->next->next;
}else{
return false;
}
slow = slow->next;
if(slow == fast)
return true;
}
return false;
}
};
Follow up:
Can you solve it without using extra space?
判断链表是否有环:使用追赶的方法,设定两个指针slow、fast,从头指针开始,每次分别前进1步、2步。如存在环,则两者相遇;如不存在环,fast遇到NULL退出。
/**
* 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 *slow = head;
ListNode *fast = head;
while(head){
if(fast->next && fast->next->next){
fast = fast->next->next;
}else{
return false;
}
slow = slow->next;
if(slow == fast)
return true;
}
return false;
}
};
相关文章推荐
- [C语言][LeetCode][142]Linked List Cycle II
- [LeetCode]Linked List Cycle
- Leetcode Linked List Cycle
- [LeetCode#142]Linked List Cycle II
- leetcode-Linked List Cycle II 链表判环以及求环起始位置
- leetcode 刷题之路 59 Linked List Cycle II
- leetcode - Linked List Cycle II
- Leetcode_linked-list-cycle(c++ and python version)
- <leetcode系列> Linked List Cycle II
- LeetCode | Linked List Cycle
- [Leetcode]Linked List Cycle
- LeetCode Linked List Cycle
- [LeetCode] Linked List Cycle II
- Linked List Cycle II (LeetCode)
- LeetCode——Linked List Cycle
- leetcode(141). Linked List Cycle
- leetcode Linked List Cycle
- leetcode Linked List Cycle II
- leetcode解题之141# Linked List Cycle Java版 (判断链表是否有环)
- LeetCode141:Given a linked list, determine if it has a cycle in it.