Return true if a singly linked list contains a cycle. Otherwise return false.
You get the head of the list. A cycle means some node's next points back to an earlier node in the list. Then following next never reaches null.
headcan benull. In that case, returnfalse.- A single node whose
nextis itself is a cycle. - The list can hold up to 100,000 nodes.
- Values can repeat. So you can't find a cycle by looking for a repeated value.
- Use only O(1) extra memory, which means a fixed amount that doesn't grow with the list. So no
Set,Mapor array of visited nodes. Also, don't change the nodes.
Input: 3 → 1 → 7 → 4, and 4's next points back to 1
Output: true
Input: 3 → 1 → 7 → 4 → null
Output: false