LeetCode *** 141. Linked List Cycle
来源:互联网 发布:nestopia mac 金手指 编辑:程序博客网 时间:2024/04/29 12:51
题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
分析:
利用set比较简单,就不多说了。
同时可以利用一个走的快的与一个走的慢的来进行对比,如果有circle那么走得快的与走得慢始终会相遇。
代码:
利用set:
/** * 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) { set<ListNode*> record; while(head){ if(!record.insert(head).second)return true; head=head->next; } return false; }};
without using extra space:
/** * 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=head,*slow=head; while(fast&&fast->next){ fast=fast->next->next; slow=slow->next; if(fast!=NULL&&slow!=NULL&&fast==slow)return true; } return false; }};
0 0
- [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
- 141. Linked List Cycle LeetCode
- [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
- 141.[LeetCode]Linked List Cycle
- 【leetcode】141. Linked List Cycle
- 数据挖掘/机器学习 之 距离测度
- sigmoid
- linux文档详解
- 设计模式之策略(Strategy)模式
- mysqlwhere子句进行条件选择
- LeetCode *** 141. Linked List Cycle
- 文章标题
- 广东工业大学2016校赛 Problem A: Krito的讨伐
- Hadoop中fsimage和edits合并问题
- hadoop过程
- Mysql中的Cascade,NO ACTION,Restrict,SET NULL
- quad积分函数的使用的四种方法
- [number theory]数论
- Mybatis 中sql 使用in(#{item})无法查询解决办法