一、环
![](https://i-blog.csdnimg.cn/blog_migrate/48cc875ac8cf20897ac487feb9346504.png)
二、创建环
//建立环
public void createLoop(){
Entry cur = this.head;
while(cur.next != null){
cur = cur.next;
}
Entry cur2 = this.head.next.next.next;
cur.next = cur2;//和第三个数据结点构成一个环
}
三、判断是否有环
//判断一个单链表中是否有环
public boolean isLoop(){
//快指针和慢指针从head出发
Entry fast = this.head;
Entry slow = this.head;
while(fast != null && fast.next != null){
//fast每走两步,slow走一步
fast = fast.next.next;
slow = slow.next;
if(slow == fast){//有环的话,fast和slow迟早会相遇
return true;
}
}
//没有相遇就没有环
return false;
}
四、环的入口点
//环的入口点
public int enterEntry(){
Entry fast = this.head;
Entry slow = this.head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(slow == fast){
break;
}
}
slow = this.head;
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
return slow.data;
}
五、环的长度
//环的长度
public int loopLength(){
Entry fast = this.head;
Entry slow = this.head;
boolean flag = false;//标记
int len = 0;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(slow == fast && flag == true){
break;
}
if(slow == fast && flag == false){
flag = true;//第一次相遇将flag置为true
}
if(flag == true){
len ++;
}
}
return len;
}