From the course: C# Algorithms
Unlock this course with a free trial
Join today to access over 25,300 courses taught by industry experts.
Solution: detect a cyclic linkedlist - C# Tutorial
From the course: C# Algorithms
Solution: detect a cyclic linkedlist
Let's create an algorithm that detects if a linked list has a cycle. In order to determine if there's a cycle, we need to use the next pointers of the linked list. We need to check that a given next pointer is not pointing to a node we've already seen in the list. This is a question of membership, which makes the HashSet a great tool for this algorithm. In our code, we'll iterate through the linked list, and every time we see a new node, we'll check if it's in the HashSet. If it's not, we'll add it to the set. If it is in the HashSet, this means we've seen the node before and there is a cycle in the list. If we're able to get through the entire list without seeing the same node twice, then there's not a cycle in the list. Let's implement this idea in code. To start, we'll create a new HashSet that will store the nodes we've already seen in the list. Then we'll create a current reference that will keep track of where we are in the list. While the current is not equal to null, there are…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.