LeetCode -- LinkedListCycle
2014-07-14 22:12
218 查看
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) {}
* };
*/
用两个指针,一个每次前进1步,一个每次前进2步,如果存在环,那么两个指针就终会相遇。要注意判断快慢针前进过程中是否会是NULL。
class Solution{
public:
bool hasCycle(ListNode *head){
ListNode *pointer1 = head;
ListNode *pointer2 = head;
while(1){
if(pointer1 == NULL) return false;
pointer2 = pointer2 ->next;
if(pointer2 == NULL) return false;
pointer2 = pointer2 ->next;
if(pointer2 == NULL) return false;
if(pointer2 == pointer1)return true;
pointer1 = pointer1 ->next;
}
}
}
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) {}
* };
*/
用两个指针,一个每次前进1步,一个每次前进2步,如果存在环,那么两个指针就终会相遇。要注意判断快慢针前进过程中是否会是NULL。
class Solution{
public:
bool hasCycle(ListNode *head){
ListNode *pointer1 = head;
ListNode *pointer2 = head;
while(1){
if(pointer1 == NULL) return false;
pointer2 = pointer2 ->next;
if(pointer2 == NULL) return false;
pointer2 = pointer2 ->next;
if(pointer2 == NULL) return false;
if(pointer2 == pointer1)return true;
pointer1 = pointer1 ->next;
}
}
}
相关文章推荐
- LeetCode刷题笔录Linked List Cycle
- [LeetCode]Linked List Cycle
- 141. Linked List Cycle LeetCode
- leetcode(142). Linked List Cycle II
- leetcode - Linked List Cycle
- leetcode: Linked List Cycle
- LeetCode题解:Linked List Cycle
- leetcode题目:Linked List Cycle和Linked List Cycle II
- leetcode — linked-list-cycle
- leetcode:linked_list_cycle_II
- LeetCode-Easy刷题(32) Linked List Cycle
- LeetCode: Linked List Cycle II
- 【Leetcode】Linked List Cycle
- leetcode--Linked List Cycle &Linked List Cycle II
- Leetcode 线性表 Linked List Cycle
- LeetCode:Linked List Cycle
- Leetcode Linked List Cycle
- 【leetcode刷题笔记】Linked List Cycle
- [LeetCode] Linked List Cycle II
- Linked List Cycle leetcode java (链表检测环)