判斷鏈表是否循環,找出循環點。
例子: 輸入, A->B->C->D->E->C
輸出: C
class Node {
char data;
Node next;
Node(char d, Node n) {
data = d;
next = n;
}
Node(char d) {
this(d, null);
}
}
public class CicularList {
public static void main(String[] args) {
Node head = new Node('A');
head.next = new Node('B');
Node sloop = head.next.next = new Node('C');
sloop.next = new Node('D', new Node('E', sloop));
Node thead = head;
for (int i = 0; i < 6; i++) {
System.out.println(thead.data);
thead = thead.next;
}
System.out.println(isCicularList(head));
System.out.println(findLoopNode(head));
}
public static Node findMeetPoint(Node head){
if (head == null)
return null;
Node slow = head;
Node fast = head;
while ((slow = slow.next) != null && (fast = fast.next.next) != null
&& slow != fast)
;
if (slow == null || fast == null)
return null;
return slow;
}
public static Node findLoopNode(Node head){
Node fast = null;
if(null ==(fast = findMeetPoint(head))) return null;
Node slow = head;
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
System.out.println(fast.data);
return fast;
}
public static boolean isCicularList(Node head) {
if (head == null)
return false;
Node slow = head;
Node fast = head;
while ((slow = slow.next) != null && (fast = fast.next.next) != null
&& slow != fast)
;
if (slow == null || fast == null)
return false;
return true;
}
}