Linked List Cycle II
ID: 142; medium
Solution 1 (Go)
Solution 2 (Go)
Solution 3 (Java)
Last updated
ID: 142; medium
Last updated
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func detectCycle(head *ListNode) *ListNode {
m := make(map[*ListNode]bool)
for head != nil {
if _,found := m[head]; found {
return head
}
m[head] = true
head = head.Next
}
return nil
}/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func detectCycle(head *ListNode) *ListNode {
hasCycle, tortoise := hasCycle(head)
if head == nil || head.Next == nil || !hasCycle {
return nil
}
hare := head
// both move by 1 and look for second meet
for tortoise != hare {
tortoise = tortoise.Next
hare = hare.Next
}
return tortoise
}
// from ID: 141
func hasCycle(head *ListNode) (bool, *ListNode) {
tortoise, hare := head, head
for tortoise != nil && hare != nil && hare.Next != nil {
tortoise = tortoise.Next
hare = hare.Next.Next
if tortoise == hare {
return true, tortoise
}
}
return false, nil
}/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: The node where the cycle begins. if there is no cycle, return null
*/
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null)
return null;
ListNode slow = head;
ListNode fast = head.next;
// slow and fast meet for the first time
while (slow != fast) {
if (fast == null || fast.next == null)
return null;
slow = slow.next;
fast = fast.next.next;
}
// the second meeting point is the start of the cycle
fast = fast.next;
while (head != fast) {
head = head.next;
fast = fast.next;
}
return head;
}
}