142. Linked List Cycle II 找到环的起始位置

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.

 

Follow up:
Can you solve it without using extra space?

思路:用hashset把每个节点存起来,每次遍历到新的节点,如果hashset中存在了,那么就有环,即当前节点

但是显然是开辟了空间

但是leetcode还是通过了

public class Solution {
    public ListNode detectCycle(ListNode head) {
        HashSet hashSet = new HashSet();
        ListNode l = head;
        while (l!=null){
            if(hashSet.contains(l)){
                return l;
            }else {
                hashSet.add(l);
                l = l.next;
            }
        }
        return null;
    }
}

去找大神看大神的做法:

思路:先用快慢指针判断是否有环,如果有环,让慢指针指向头节点,两个指针以相同的速度(+1)遍历,两指针相等的就是我们要的:

public ListNode detectCycle(ListNode head) {
	ListNode slow = head;
	ListNode fast = head;
	while ((fast != null) && (fast.next != null)) {
		slow = slow.next;
		fast = fast.next.next;
		if (slow == fast) 
			break;
	}
	// if no loop then return
	if ((fast == null) || (fast.next == null)) 
		return null;
	// there's a loop
	slow = head;
	while (slow != fast) {
		 slow = slow.next;
		 fast = fast.next;
	}
	return slow; // or fast
}

断链法

链接:https://www.nowcoder.com/questionTerminal/253d2c59ec3e4bc68da16833f79a38e4
来源:牛客网

两个指针,一个在前面,另一个紧邻着这个指针,在后面。
两个指针同时向前移动,每移动一次,前面的指针的next指向NULL。
也就是说:访问过的节点都断开,最后到达的那个节点一定是尾节点的下一个,
也就是循环的第一个。
这时候已经是第二次访问循环的第一节点了,第一次访问的时候我们已经让它指向了NULL,
所以到这结束。

 

你可能感兴趣的:(数据结构,java面试,leetcode)