Linked List Cycle
2016-02-01 09:34
211 查看
两个指针系列
This question is just something like if you know the trick then you can do it, otherwise just no way to solve it.
Note:
1. The faster one move 2 steps and slower one move one step each time
2. Be careful when you are access node->next, you should check node first. same logic apply to node->next->next
3. Regarding head node, handle the special cases first.
Just to make the code cleaner, there is no need to check
at the begin, you can embed this also inside of the while loop, but it make more clear if we check at the beginning.
Follow up:
Solve it without extra space O(1) solution. This is already a solution with O(1) space since it just create a pointer point to existing one but no new or malloc so it is still O(1).
This question is just something like if you know the trick then you can do it, otherwise just no way to solve it.
Note:
1. The faster one move 2 steps and slower one move one step each time
2. Be careful when you are access node->next, you should check node first. same logic apply to node->next->next
3. Regarding head node, handle the special cases first.
class Solution { public: bool hasCycle(ListNode *head) { if (head == NULL || head->next == NULL) return false; ListNode *n1 = head; ListNode *n2 = head; while (n2 != NULL && n2->next != NULL) { n2 = n2->next->next; n1 = n1->next; if (n2 == n1) return true; } return false; } };
Just to make the code cleaner, there is no need to check
if (head == NULL || head->next == NULL)
at the begin, you can embed this also inside of the while loop, but it make more clear if we check at the beginning.
Follow up:
Solve it without extra space O(1) solution. This is already a solution with O(1) space since it just create a pointer point to existing one but no new or malloc so it is still O(1).
相关文章推荐
- 递归式求解的三种方法
- Struts2 语法--result type
- sqlserver 随机数
- php--mysqli扩展库之增、删、改、查
- 搜索技术之我不懂的东西?
- remove()和直接使用system的一个差别
- 为js的String对象添加replaceall属性
- uninstall 11.2.0.3.0 grid & database in linux 5.7
- Netty初步之Hello World
- 326. Power of Three
- oracle数据库字符集AL32UTF8修改为ZHS16GBK即从超集到子集
- Android Design Support Library控件使用总结(一)
- swift-函数-1
- Linux上pip安装cx_Oracle
- React 入门实例教程
- CSS 参考文档
- oracle11g RAC添加节点
- 等高分栏布局小结
- 浅谈Linux内存管理机制
- Angular.js(出库编辑)