Linked List Cycle
Problem
- Return true if there is a cycle in the linked list. Otherwise, return false.
Approach
- 1. Keep looping the one node fast as twice as the other until they either run into eachother or exit the linked list
Reflections
I also did the hashmap version
func hasCycle(head *ListNode) bool {
m := make(map[*ListNode]bool)
node := head
for node != nil {
if m[node] {
return true
}
m[node] = true
node = node.Next
}
return false
}
Go Solution
func hasCycle(head *ListNode) bool {
slow,fast := head,head
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
if slow == fast {
return true
}
}
return false
}