题目:
有一个单向链表,表中可能出现环,怎么判断是否有环。
思路:
首先创建两个指针p1和p2,让他们同时指向这个链表的头结点,然后开始一个大的循环,在循环体中,让指针p1每次向后移动一个结点,让p2每次向后移动2个结点,然后比较两个指针指向的结点是否相同,如果相同,则可以判断出链表有环,如果不同,继续下一次循环。
getRingLength则是来计算环长度的
public class isCycle {
public static boolean isCycle(Node head){
Node p1 = head;
Node p2 = head;
while(p2!=null && p2.next !=null){
p1 = p1.next;
p2 = p2.next.next;
if(p1 == p2){
return true;
}
}
return false;
}
public static int getRingLength(Node head){
int RingLength = 0;
Node fast = head;
Node slow = head;
for(;;){
fast = fast.next.next;
slow = slow.next;
RingLength++;
if(fast == slow){
break;
}
}
return RingLength;
}
private static class Node{
int data;
Node next;
Node(int data){
this.data = data;
}
}
public static void main(String[] args) throws Exception{
Node node1 = new Node(5);
Node node2 = new Node(3);
Node node3 = new Node(7);
Node node4 = new Node(8);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node2;
System.out.println(isCycle(node1));
System.out.println(getRingLength(node1));
}
}