Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make a cycle in an immutable linked list?

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:

enter image description here

like image 450
Vladimir Kostyukov Avatar asked Aug 14 '13 10:08

Vladimir Kostyukov


People also ask

Can a linked list have a cycle?

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.

What is a cycle in linked list?

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.


1 Answers

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)
like image 106
senia Avatar answered Nov 04 '22 17:11

senia