Linked List Cycle II
来源:互联网 发布:三菱plc编程手册下载 编辑:程序博客网 时间:2024/06/03 17:20
Linked List Cycle II
slow指针每次走1步,fast指针每次走2步。如果链表有环,那么两个指针一定会相遇。
设链表头到环入口结点的结点数目是a,环内的结点数目r。假设相遇时,fast指针已经绕环转了n圈,比slow多走了n*r步。假设环的入口结点到相遇结点的结点数目为x。
那么在相遇时,slow走了a+x步,fast走了a+x+n*r步。
由于fast的步调是slow的两倍,所以有a+x = n*r。因而,a = n*r - x
显然,从相遇位置开始,走n*r - x步,一定可以到达环的入口结点;从链表头开始,走a步,也会到达环的入口。并且我们得到了a = n*r - x。所以我们让两个指针,一个从相遇位置出发一个从链表头出发,让他们都单步前进。因为a = n*r - x,所以他们一定会在环的入口相遇。
public ListNode detectCycle(ListNode head) { if (head == null) { return null; } ListNode slow = head; ListNode fast = head.next; boolean meet = false; int len = 0; // 判断是否有环,并计数 while (fast != null) { if (fast.next == null || fast.next.next == null) { return null; } if (slow == fast) { if (meet) { break; } meet = true; } fast = fast.next.next; slow = slow.next; if (meet) { len++; } } if (meet) { slow = head; fast = head; // fast先走len步 for (int i = 0; i < len; i++) { fast = fast.next; } // slow从起始点出发,fast从len处出发 // 二者相遇的结点,即为入环结点 while (slow != fast) { slow = slow.next; fast = fast.next; } return slow; } return null; }
阅读全文
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
- 百度地图点聚合自定义marker
- 解决Bootstrap 模态对话框只加载一次请求数据问题
- 浅谈Java中的hashcode方法
- flask response对象
- RxJava学习2--类型转换
- Linked List Cycle II
- 百度地图-3.Hello BaiduMap
- [mongoDB]SSM整合mongoDB3.4配置文件
- 【NIPS最佳论文引发深度学习论战】AlphaZero能击败冷扑大师吗?No(Science论文)
- Java获取系统时间的四种方法
- java自定义注解基础
- Nginx 安装配置
- 【几点总结】开漏极
- 数学 指数