链表环查找(Linked List Cycle II)
来源:互联网 发布:中国十大海滩知乎 编辑:程序博客网 时间:2024/06/05 10:10
问题:
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull
.
Follow up:
Can you solve it without using extra space?
在链表中查找环,并且判断起始位置,本能反应时对已经走过的节点进行标记,如果有再次访问则有环,且起点为该点。但是要求without using extra space。所以只能换个思路。 判断单链表是否存在环及寻找环的入口点文章里写了三个方案,很清晰,自己整理了下选择了fast ,slow指针法。
推理过程:
1.fast和slow每次分别走2步,1步,如果有环则一定会相遇。
2.针对查找开始点,总结起来就是相遇后fast从头开始走每次一步,下一次和slow相遇的地方为循环开始的地方。
如图起始点为O,fast和slow相遇点为A,循环起始点为P。则|OP|+|PA| = |OA|,|OA|为slow走过了路线长,设定为n,则fast走过2n,所以slow在走n步会回到A点。而fast从头走n步也会到大A点,所以在fast和slow下次相遇时一定是在P处,即没有完全走完n步(除非相遇在P)。
代码 :
ListNode *detectCycle(ListNode *head) { ListNode * fast = head, * slow = head; while(fast != NULL && fast->next != NULL) { fast = fast->next->next; slow = slow->next; if(fast == slow) break; } if(fast == NULL || fast->next == NULL ) return NULL; //无环 else { fast = head; while( fast != slow ) { fast = fast->next; slow = slow->next; } return fast; } }又写了几个测试,测试各种特殊情况,测试通过,上传。
蛮顺利~fighting~~
前两天的二叉树便利和列表排序没写,但是两个都蛮简单的。
0 0
- 链表环查找(Linked List Cycle II)
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- 企业如何管理好业务代表
- eclipse安装SVN插件的两种方法
- 关于 友盟(android)
- Cocostudio使用小技巧
- 详解Widget组件及设计介绍
- 链表环查找(Linked List Cycle II)
- 故事板Storyboard
- ios view的frame和bounds之区别(位置和大小)
- 新网站如何22权重1
- java ThreadPoolUtil
- 自定义控件
- java 编写用于完成四则运算的类
- CentOS下一键安装GitLab
- iOS7新特性