Given
head
, the head of a linked list, determine if the linked list has a cycle in it.There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the
next
pointer. Internally,pos
is used to denote the index of the node that tail'snext
pointer is connected to. Note thatpos
is not passed as a parameter.Return
true
if there is a cycle in the linked list. Otherwise, returnfalse
.
Difficulty
- Level: Easy
- Acceptance: 42.6%
Solution
Analysis
I used a set in my solution as sets are great with dealing with large amounts of data in comparison to an array, good for searching, and great for unique values.
While the head is not null, the algorithm will check if the set has a reference to the node. If not, it will be added to the set and the reference for the head will point to the next node. If so, it will return true. If we have reached the end of the linked list and there are still no matches with the set, we shall return false.