Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Note: Do not modify the linked list.
Example 1:
1 2 3
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:
1 2 3
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:
1 2 3
Input: head = [1], pos = -1 Output: no cycle Explanation: There is no cycle in the linked list.
思路0
哈希表,如果我們用一個 Set 保存已經訪問過的節點,我們可以遍歷整個列表並返回第壹個出現重復的節點。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
publicclassSolution{ public ListNode detectCycle(ListNode head){ Set<ListNode> visited = new HashSet<ListNode>();
ListNode node = head; while (node != null) { if (visited.contains(node)) { return node; } visited.add(node); node = node.next; }
// A fast pointer will either loop around a cycle and meet the slow // pointer or reach the `null` at the end of a non-cyclic list. while (hare != null && hare.next != null) { tortoise = tortoise.next; hare = hare.next.next; if (tortoise == hare) { return tortoise; } }
returnnull; }
public ListNode detectCycle(ListNode head){ if (head == null) { returnnull; }
// If there is a cycle, the fast/slow pointers will intersect at some // node. Otherwise, there is no cycle, so we cannot find an e***ance to // a cycle. ListNode intersect = getIntersect(head); if (intersect == null) { returnnull; }
// To find the e***ance to the cycle, we have two pointers traverse at // the same speed -- one from the front of the list, and the other from // the point of intersection. ListNode ptr1 = head; ListNode ptr2 = intersect; while (ptr1 != ptr2) { ptr1 = ptr1.next; ptr2 = ptr2.next; }