Suppose that we have the following structure in Java:
class List {
// we're immutable
final List next;
final int value;
public List(int value, List next) {
this.next = next;
this.value = value;
}
}
Scala has built-in support for immutable singly-linked list. It would be:
val l = List(1, 2, 3) // immutable
So, is it possible to make a cycle in this kind of lists (immutable singly-linked list). By cycle, I mean the following:
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's next pointer is connected to.
A cycle occurs when a node's next points back to a previous node in the list. The linked list is no longer linear with a beginning and end—instead, it cycles through a loop of nodes.
You should use lazy
collection to create infinite collection. You could use Stream
:
def loopStream: Stream[Int] = {
lazy val loop: Stream[Int] = 3 #:: 4 #:: 5 #:: 6 #:: 7 #:: 8 #:: loop
1 #:: 2 #:: loop
}
loopStream.take(22).toList
// List(1, 2, 3, 4, 5, 6, 7, 8, 3, 4, 5, 6, 7, 8, 3, 4, 5, 6, 7, 8, 3, 4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With