【Leetcode】Linked List Cycle

714 ワード

原題リンク:https://leetcode.com/problems/linked-list-cycle/
タイトル:
Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
考え方:
2つのポインタ、1つは1歩、1つは2歩移動するので、2つのポインタは相対的に距離が移動するたびに1つ加算され、サイクルがあれば必ずサイクル長/(2-1)サイクル後に出会うことができ、サイクルがなければnullに遭遇する.
アルゴリズム:
	public boolean hasCycle(ListNode head) {
		ListNode q = head, p = null;// p   ,q   
		if (q == null || q.next == null) {//        
			return false;
		}
		p = q.next.next;
		while (p != null) {
			if (q == p) {
				return true;
			}
			if (p.next == null) {// p   ,   p.next  
				return false;
			}
			p = p.next.next;
			q = q.next;
		}
		return false;
	}