leetcode - Linked List Cycle II
2015-07-14 17:53
489 查看
leetcode - Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Follow up:
Can you solve it without using extra space?
两个指针ptr1和ptr2,都从链表头开始走,ptr1每次走一步,ptr2每次走两步,等两个指针重合时,就说明有环,否则没有。如果有环的话,那么让ptr1指向链表头,ptr2不动,两个指针每次都走一步,当它们重合时,所指向的节点就是环开始的节点。
http://blog.sina.com.cn/s/blog_6f611c300101fs1l.html#cmt_3246993
Given a linked list, return the node where the cycle begins. If there is no cycle, return
null.
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: ListNode *detectCycle(ListNode *head) { if(NULL == head || NULL == head->next) return NULL; ListNode *p1 = head->next; ListNode *p2 = head->next->next; while(p2 != NULL && p2->next != NULL && p1 != p2){ p1 = p1->next; p2 = p2->next->next; } if(p1 == p2){ ListNode *tp = head; while(tp != p2){ tp=tp->next; p2=p2->next; } return tp; } else return NULL; } };
两个指针ptr1和ptr2,都从链表头开始走,ptr1每次走一步,ptr2每次走两步,等两个指针重合时,就说明有环,否则没有。如果有环的话,那么让ptr1指向链表头,ptr2不动,两个指针每次都走一步,当它们重合时,所指向的节点就是环开始的节点。
http://blog.sina.com.cn/s/blog_6f611c300101fs1l.html#cmt_3246993
相关文章推荐
- 浏览器是怎样工作的:渲染引擎,HTML解析
- Android中日期与时间设置控件用法实例
- Python下opencv使用笔记(九)(图像直方图)
- golang(4):编写socket服务,简单支持命令
- [ActionSprit 3.0] FMS直播
- windows 文件或文件夹权限问题
- hdu 1710 Binary Tree Traversals
- R语言学习(1)线性模型
- textview根据字数自动调高度,cell高度自动调节
- DOM
- 共谋节点两个单列表
- MyEclipse 8.6中的Drools安装配置
- Linux之VI常用命令
- 在Ubuntu 15.04中安装Ruby on Rails
- Merge k Sorted Lists
- Xcode编译 No such file or directory
- Cocos2d-x3.0下一个 Lua与C++打电话给对方
- EntityFramework 5.0 CodeFirst 教程02-删除和修改/架构改变异常的处理
- MongoDB数据实体中的ObjectId序列化成json的一个小坑
- 绚盘源码分析