You can create a linked list structure in Java using Nodes.
class Node {
Node next;
// some user data
}
If there is a possibility that the list can contain a loop, then instead of the last Node having a null for the next reference, it could have a reference to one of the nodes in the list which came before it.
What's the best way of writing
Write a function that traverses the list and keeps track of seen nodes in a set. If the given Node is in the set, return false; if the end of the list is reached without the given Node being in the set, return true. This would take a constant amount of space and a linear amount of time.
This is an example of a list constructed with a loop:
Unpublished comment
Viết câu trả lời