[LeetCode]Linked List Cycle
2014-04-28 01:05
323 查看
Question:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Answer:
/**
* 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 *first = head;
ListNode *second = head;
while (second && second -> next)
{
first = first -> next;
second = second -> next -> next;
if (first == second) return true;
}
if (second == NULL || second -> next == NULL) return false;
}
};
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Answer:
/**
* 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 *first = head;
ListNode *second = head;
while (second && second -> next)
{
first = first -> next;
second = second -> next -> next;
if (first == second) return true;
}
if (second == NULL || second -> next == NULL) return false;
}
};
相关文章推荐
- LeetCode——linked-list-cycle-ii
- 【Leetcode】Linked List Cycle
- [leetcode] 141& 142 Linked List Cycle I& II
- LeetCode_Linked List_Linked List Cycle II
- LeetCode刷题(C++)——Linked List Cycle(Easy)
- LeetCode: Linked List Cycle II
- LEETCODE--Linked List Cycle
- LeetCode 141: Linked List Cycle
- 【leetcode82】Linked List Cycle
- [leetcode] Linked List Cycle
- [LeetCode]142 Linked List Cycle II
- 【Leetcode】Linked List Cycle
- Leetcode141——Linked List Cycle
- [leetcode][list][two pointers] Linked List Cycle II
- LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal
- LeetCode: Linked List Cycle I && II
- 【leetcode】Linked List Cycle
- LeetCode(6):linked-list-cycle
- Linked List Cycle——LeetCode
- leetcode linked-list-cycle(i 、ii)(java实现)