Linked List Cycle
来源:互联网 发布:利用php漏洞进行提权 编辑:程序博客网 时间:2024/06/03 17:50
Description:
Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
分析
最容易想到的方法是,用一个哈希表 unordered_map< int, bool > visited,记录每个元素是否被访问过,一旦出现某个元素被重复访问,说明存在环。空间复杂度 O(n),时间复杂度 O(N )。
最好的方法是时间复杂度 O(n),空间复杂度 O(1) 的。设置两个指针,一个快一个慢,快的 指 针 每 次 走 两 步, 慢 的 指 针 每 次 走 一 步, 如 果 快 指 针 和 慢 指 针 相 遇, 则 说 明 有 环。
#include <iostream>#include <limits.h>using namespace std;struct LNode{ int val; LNode *next; LNode(int x):val(x),next(nullptr) {}};class Solution{ public: bool hasCircle(LNode *L) { if (L == nullptr || L->next == nullptr) return false; LNode *slow = L, *fast = L; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) return true; } return false; }};int main(void){ LNode *List = new LNode(INT_MIN); LNode *ptr = List; int n; cout<<"Input the number: "<<endl; cin>>n; for (int i =0; i < n; i++) { ptr->next = new LNode(i); ptr = ptr->next; } ptr->next = List->next; //circle Solution solution; bool result = solution.hasCircle(List->next); if (result) cout<<"The list has a circle."<<endl; else cout<<"There is no circle in the list."<<endl; LNode *pointer = List; for (int i = 0 ;i <= n; ++i) { pointer = List->next; delete List; List = pointer; } return 0;}
0 0
- leetcode Linked List Cycle & Linked List Cycle ||
- Linked List Cycle II Linked List Cycle
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle II
- [LeetCode]Linked List Cycle
- Linked List Cycle
- LeetCode | Linked List Cycle
- yii2.0如何获取当前的控制器名与方法名
- leetcode之delete Node in a Linked List
- 背包--nkoj3609【USACO 2015 Dec Gold】Fruit Feast
- 化繁为简 如何向老婆解释MapReduce?
- 正则表达式带有双引号 如何去掉 js里用
- Linked List Cycle
- centos7安装mate
- AnimMontage(中文翻译)——UE4官方文档
- 中国县级和以下行政区编码,2013年,sql文件
- hdu1124
- Android调用相机无法执行onActivityResult或data为null
- MySQL开启慢查询
- JavaEE的13种核心技术
- linux使用X Windows设置远程桌面