leetcode || 141、Linked List Cycle
来源:互联网 发布:人防指挥所智能化软件 编辑:程序博客网 时间:2024/05/16 10:32
problem:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
thinking:
(1)如果可以开设额外的空间,使用unordered_set存储遍历过的结点,出现重复时即为存在环形结构
(2)如果不适用额外的空间,及空间复杂度为O(1),这里使用快、慢双指针。慢指针每次走一步,快指针每次走两步。
如果存在环形结构,两个指针总会相遇。
(3)终止条件也要注意:
fast!=NULL && fast->next!=NULL
防止出现fast->NULL->next
code:
/** * 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 *fast,*slow; if(head==NULL) return false; slow=head; fast=head->next; while(fast!=NULL && fast->next!=NULL) { if(slow==fast) return true; slow=slow->next; fast=fast->next->next; } return false; }};
0 0
- LeetCode(141)Linked List Cycle
- LeetCode 141 Linked List Cycle
- LeetCode 141 Linked List Cycle
- LeetCode: Linked List Cycle [141]
- [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
- 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
- 深入理解JAVA内存模型第二部分
- leetcode-Balanced Binary Tree
- 社説 20150504 群大と女子医大 病院の安全管理見直しが急務
- html基础知识(二)
- oracle入门之 DML&DCL&TCL语句
- leetcode || 141、Linked List Cycle
- 创意时钟
- #pragma详细解释
- 社説 20150504 NPT会議 核軍縮と不拡散の覚悟を示せ
- Nova是如何统计OpenStack计算资源的(转)
- z-stack协议栈sampleapp分析介绍(一)
- 如何使用Shell捕捉半夜的问题进程
- java语言实现结构型设计模式—适配器模式
- android反编译工具学习