判斷鏈表是否循環,找出循環點

判斷鏈表是否循環,找出循環點。

例子: 輸入, 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;
	}
}


發佈了50 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章