检测一个链表是否有环

package java程序员面试笔试宝典;


public class 题8_1_7检测一个链表是否有环{
public static void main(String[] args) {
题8_1链表基本操作 list=new 题8_1链表基本操作();
list.addNode(3);
list.addNode(2);
list.addNode(1);
list.addNode(8);
list.addNode(7);
list.addNode(13);
list.addNode(0);
list.addNode(10);
//System.out.println(list.getNode(7).data);
list.getNode(7).next=list.getNode(4);
//System.out.println(mylist.isLoop(list.head));

System.out.println(findLoopPort(list.head).data);
}
public static Node findLoopPort(Node head){
Node fast=head;
fast=fast.next.next;
Node slow=head;
slow=slow.next;
while(fast!=slow){
fast=fast.next.next;
slow=slow.next;
}
//System.out.println(fast.data);
Node q=head;
while(slow!=q){
q=q.next;
slow=slow.next;
}
return q;
}
public boolean isLoop(Node head){
Node fast=head;
Node slow=head;
if(fast==null){
return false;
}
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
System.out.println("有环");
return true;
}

}
System.out.println("无环");
return false;
}
}

猜你喜欢

转载自blog.csdn.net/m0_38068868/article/details/80286887