[Leetcode]Linked List Cycle II
2015-10-08 15:00
417 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
null.
Note: Do not modify the linked list.
Follow up:
Can you solve it 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: /*algorithm : hash solution time O(n) space O(n) */ ListNode *detectCycle(ListNode *head) { unordered_set<ListNode*>table; ListNode* p = head; while(p){ if(table.count(p))return p; table.insert(p); p = p->next; } return NULL; } };
class Solution { public: /*algorithm : two pointer solution faster slower runner time O(n) space O(1) */ ListNode *detectCycle(ListNode *head) { if(!head)return NULL; ListNode* faster = head,*slower = head; do{ slower = slower->next; faster = faster->next; if(faster)faster = faster->next; }while(faster && faster != slower); if(!faster)return NULL; //no cycle // slower = head; while(slower != faster){ slower = slower->next; faster = faster->next; } return slower; } };
相关文章推荐
- bootstrap中modal的简单使用
- hadoop1.2.1+zk-3.4.5+hbase-0.94.1集群安装过程详解
- jvm工具系列之 -- jstat
- 浮点型在计算机中的存储表示
- winform中使用webBrowser时如何与JS交互
- 转载 -- CSS3 中关于 select 下拉列表的样式
- 在自定义的web监听器中嵌入web中的定时事件
- ffmpeg
- cdoj 86 Divide
- JDBC详解
- 猫爪不能在下,页脚不能在上
- jquery类选择器及其遍历
- python下很帅气的爬虫包 - Beautiful Soup 示例
- 构筑RubyMine IDE开发工具的Coffeescript+node.js开发环境(for windows)
- 猫爪不能在下,页脚不能在上
- 查某张表中某字段重复记录大于1的语句
- android 中 编写jni
- 静思
- POJ 3495 Bitwise XOR of Arithmetic Progression 数论
- UI最佳实践的N条建议