leetCode--linked-list-cycle-ii
来源:互联网 发布:银河证券手机炒股软件 编辑:程序博客网 时间:2024/06/08 10:53
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?
分析:
串长a + n,其中n为循环,当a + b步的慢指针与快指针相遇时,快指针已经走过了k圈。
即a + b + k * n = 2 * (a+b),求a,得到a = k * n - b。
也就是X走a步,等于Z位置上的指针再走k圈,相遇于Y点。
/** * 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) { if(head==null||head.next==null){ return null; } ListNode slow=head; ListNode fast=head; while(fast!=null&&fast.next!=null){ slow=slow.next; fast=fast.next.next; if(slow==fast){ ListNode slow2=head; while(slow2!=slow){ slow2=slow2.next; slow=slow.next; } return slow; } } return null; }}
阅读全文
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
- 非对称加密 原理及实践
- Struts2下载及配置
- 工具使用:centOS上的防火墙
- linux网络编程之套接字编程
- 设计模式之外观模式
- leetCode--linked-list-cycle-ii
- android关于LinearLayout的坑
- 冒泡排序
- Django中中间件系列之十四
- Android studio设置activity主题程序崩溃解决办法
- Servlet中的文件上传
- java中重载与重写的区别
- Eclipse中修改注释中@author
- MyBatis集成log4j