leetcode--LinkedListCycleII
来源:互联网 发布:手机能不能做淘宝客服 编辑:程序博客网 时间:2024/06/04 00:46
思路:
1.从head开始利快慢指针分别向后遍历,快指针每次比慢指针多走一步,直到快指针和慢指针相遇。
2.创建一个新的慢指slow2针指向head,和之前的慢指针同时向后遍历,直到两个慢指针相遇,返回当前相遇的节点。
证明:
设head到达环入口start需要m步,遍历一遍环需要n步。当慢指针slow到达环入口走了m步,快指针fast比slow多走m步,赶上slow需要n-m%n步。当fast和slow相遇时slow从环入口走了n-m%n步,此时如果再走m步即n+m-m%n=n+an+r-r=bn为n的整数倍,正好停在换入口处。
public ListNode detectCycle(ListNode head) { ListNode fast=head; ListNode slow=head; boolean first=true; boolean hasCycle=false; while(fast!=null){ if(fast.next==null)break; if(fast.equals(slow)&&!first){ hasCycle=true; break; } fast=fast.next.next; slow=slow.next; first=false; } if(!hasCycle)return null; ListNode slow2=head; while(!slow2.equals(slow)){ slow2=slow2.next; slow=slow.next; } return slow; }
0 0
- leetcode--LinkedListCycleII
- LeetCode 解题报告 LinkedListCycleII
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- 1095. Cars on Campus (30)
- LintCode-删除排序数组中的重复数字
- C# 窗体 webbrowser 窗体调用javascript方法 实例
- Ubuntu下开启SSH服务
- POJ 3648 2-SAT
- leetcode--LinkedListCycleII
- js获取下拉框属性值的写法
- linux 定时调度 的 工具
- python requests encoding
- thinkphp 更新和插入记录
- Android.mk文件语法规范——深入了解android平台的jni
- Cocoapods安装遇到的问题
- POJ 2455--Secret Milking Machine【二分枚举 && 最大流 && 经典】
- Fence Repair