LeetCode *** 141. Linked List Cycle
2016-04-11 21:18
155 查看
题目:
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:
without using extra space:
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; } };
相关文章推荐
- Hadoop中fsimage和edits合并问题
- c++实验3-分段函数求值
- 很好用的一个类:TJvAppXMLFileStorage
- 2602 Bone Collector dp-3
- 理解牛顿法
- Android学习第五天,Style,和选择器
- 史上最详细c语言学生管理系统(完整的源代码)
- Python+PyQt4+Eric6合并Excel的图形化界面设计
- [number theory]数论
- tornado
- c++上机第三次实验
- NOD 1113矩阵快速幂
- nyoj 5 Binary String Matching
- 进程间通信(2)消息队列
- 递归倒序输出字符串
- ZooKeeper中“会话”的那些事儿
- 设备管控数据表设计
- 我的VS2010+VAssistX
- 关于01背包问题优化的时候为什么不能正向跑
- 生成短链(网址) ShortUrlLink