leetcode: Linked List Cycle II
来源:互联网 发布:stm32编程环境 编辑:程序博客网 时间:2024/06/08 15:13
这道题在1的基础上要我们找到环的起点。 由于环的起点不一定就是链表的起点,所以我们设链表起点到环起点距离为x,慢指针在环中走了y,慢指针走到环起点距离为z。
那么慢指针走了x+y,快指针走了x+y+z+y。 快指针走的距离是慢指针的两倍,因而得到x=z。 即快慢指针第一次相遇的时候链表起点到环起点的距离等于相遇节点到环起点的距离。 因而两个while即可。
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode detectCycle(ListNode head) { ListNode res =null; boolean is=false; if( head==null ) { return res; } ListNode st1=head,st2=head; while( st1.next!=null && st2.next!=null && st2.next.next!=null ) { st1=st1.next; st2=st2.next.next; if( st1==st2 ) { res=st1; break; } } if(res==null) { return res; } st1=head; while(st1!=st2) { st1=st1.next; st2=st2.next; } return st1; }}
0 0
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Leetcode Linked List Cycle II
- [LeetCode]Linked List Cycle II
- leetcode Linked List Cycle II
- LeetCode | Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode] - Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II
- Linked List Cycle II -- LeetCode
- LeetCode Linked List Cycle II
- [LeetCode] Linked List Cycle II
- uva 10341 - Solve It(二分查找水题)
- poj3259Wormholes
- 神、上帝以及老天爷
- IOS开发常用函数
- 广播和广播接受者知识点分类
- leetcode: Linked List Cycle II
- Tesseract 识别 Tiff 格式文件——alpha通道干扰
- Android界面——Button按钮的一些事
- XCode快捷键
- C++复数运算符重载(+与<<)
- IBM联合CSDN发布Power Linux开发测试云平台
- Android 和 js 互相调用
- 此功能分公司与城市运营产看本部门的套餐
- 黑马程序员------毕老师视频笔记第八天------面向对象(接口多态的应用示例)