

I show this because it’s important - very important - to know that the last element in a List must be the Nil element. :10: error: value :: is not a member of Int If you forget the Nil element at the end, the Scala compiler will bark at you: scala> val list = 1 :: 2 :: 3 The second approach is known as using “cons cells.” As you can see, it’s a very literal approach to creating a List, where you specify each element in the List, including the Nil element, which must be in the last position. In computer science, a linked list is a linear collection of data elements, called nodes, each pointing to the next node by means of a pointer. Thus, the new value would be the value of the parameter (val) and then the next node would take the original value and so forth. These two techniques result in the exact same List, which you can see in the REPL: scala> val list1 = List(1,2,3) I am trying to create an Insert method which takes a parameter (position) and inserts a Node into a linkedlist at that given position. Second, this is an approach you may not have seen yet: val list = 1 :: 2 :: 3 :: Nil Take the top item of the stack and add it to the visited list.

First, here’s a technique you’re probably already familiar with: val list = List(1,2,3) Depth First Search is a recursive algorithm for searching all the vertices of a graph or. There are several ways to create non-empty Lists in Scala, but for the most part I’ll use two approaches. List() = Nil Note 2: Several ways to create Lists They can be used to implement stacks, queues, and other abstract data types. You can create an empty List in Scala in two ways: scala> val empty = List()Įmpty: .type = List()īecause I haven’t given those lists a data type (like Int), the results look a little different, but if I add a type to those expressions, you’ll see that the result is exactly the same: scala> val empty1: List = List() Linked lists are often used because of their efficient insertion and deletion.
