141. Linked List Cycle #
Problem #
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Problem Summary #
Determine whether a linked list has a cycle, without using extra space.
Solution #
Use 2 pointers, where one pointer is ahead of the other. The fast pointer moves 2 steps at a time, and the slow pointer moves 1 step at a time. If a cycle exists, then the fast pointer will eventually catch up with the slow pointer after some number of loops.
Code #
package leetcode
import (
"github.com/halfrost/leetcode-go/structures"
)
// ListNode define
type ListNode = structures.ListNode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
fast := head
slow := head
for fast != nil && fast.Next != nil {
fast = fast.Next.Next
slow = slow.Next
if fast == slow {
return true
}
}
return false
}