LeetCode:Linked List Cycle
2014-08-31 16:48
281 查看
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
已AC 76ms
Follow up:
Can you solve it without using extra space?
bool hasCycle(ListNode *head) {
<span style="white-space:pre"> </span>if(head == NULL) <span style="white-space:pre"> </span>return false; <span style="white-space:pre"> </span>ListNode* pslow = head; <span style="white-space:pre"> </span>ListNode* pfast = head; <span style="white-space:pre"> </span>while(pfast != NULL && pfast ->next != NULL) <span style="white-space:pre"> </span>{ <span style="white-space:pre"> </span>pslow = pslow->next; <span style="white-space:pre"> </span>pfast = pfast->next->next; <span style="white-space:pre"> </span>if(pfast == pslow) <span style="white-space:pre"> </span>return true; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>return false; }分析:用到了快慢指针。如果快指针追上了慢指针,说明存在循环,否则没有。
已AC 76ms
相关文章推荐
- LeetCode141:Linked List Cycle
- leetcode Linked List Cycle
- leetcode || 142、Linked List Cycle II
- 【leetcode82】Linked List Cycle
- LeetCode142—Linked List Cycle II
- 【leetcode】Linked List Cycle II
- [LeetCode] 141 - Linked List Cycle
- 【Leetcode】Linked List Cycle II (Walker_Runner)
- 【Leetcode】Linked List Cycle II
- 【LeetCode】Linked List Cycle II
- [Leetcode]Linked List Cycle II
- Leetcode Linked List Cycle II
- leetcode:linked-list-cycle-ii
- Leetcode 142 Linked List Cycle II
- 【leetcode】Linked List Cycle
- leetcode---Linked List Cycle II
- leetcode:Linked List Cycle
- [LeetCode] Linked List Cycle II Solution
- [LeetCode] Linked List Cycle II
- LeetCode Linked List Cycle II