AcWing 34. 链表中环的入口结点
这道题非常经典 是采用快慢指针进行计算 相当于小学的追及问题
用数学方式可以证明 也包括求出环的个数 环入口 环内有几个结点
原题链接
给定一个链表,若其中包含环,则输出环的入口节点。
若其中不包含环,则输出null。
数据范围
节点 val 值取值范围 [1,1000]。
链表长度 [0,500]。
代码案例:给定如上所示的链表:
[1, 2, 3, 4, 5, 6]
2
注意,这里的2表示编号是2的节点,节点编号从0开始。所以编号是2的节点就是val等于3的节点。
则输出环的入口节点3.
题解
用两个指针 first,second 分别从起点开始走,first 每次走一步,second 每次走两步。 图中的因为速度差是二倍 第一次相遇走的路程也是它的二倍
求出 a+b = k*s k 是走过的环的次数 s是环的周长
如果过程中 second 走到null,则说明不存在环。
否则当 first 和 second 相遇后,让 first 返回起点,second 待在原地不动,等到first从起点出发 一起走 然后两个指针每次分别走一步, 这时候二者速度一样
当相遇时,相遇点就是环的入口。也就是a相当于环中减掉b的那部分 相遇点就是环的入口处
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
class Solution {
public ListNode entryNodeOfLoop(ListNode head) {//判断环的入口 定义快慢指针
if(head==null || head.next==null){//空结点判定
return null;
}
ListNode fast=head;
ListNode slow=head;
int ringLength=1;
while(fast.next!=null && fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){//二者相遇
slow=slow.next;
while(fast!=slow){
slow=slow.next;
ringLength++;
}
fast=slow=head;
for(int i=0;i<ringLength;i++){
fast=fast.next;
}
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}
return fast;
}
}
return null;
}
}
两种习惯写法
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
class Solution {
public ListNode entryNodeOfLoop(ListNode head) {
if(head==null || head.next==null){//空结点判定
return null;
}
ListNode first=head;
ListNode second=head;
while (first != null && second != null)
{
first = first.next;
second = second.next;
if (second != null) second = second.next;
if (first == second)
{
first = head;
while (first != second)
{
first = first.next;
second = second.next;
}
return first;
}
}
return null ;
}
}