Created
December 5, 2011 15:55
-
-
Save flazz/1434052 to your computer and use it in GitHub Desktop.
list.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class LinkedList[T] { | |
def add(someV: T) = new Node(someV, this) | |
def get(index: Int):T | |
def length:Int | |
} | |
class Empty[T] extends LinkedList[T] { | |
def get(_index: Int) = sys.error("index out of bounds") | |
def length = 0 | |
override def toString = "" | |
} | |
class Node[T](value: T, next: LinkedList[T]) extends LinkedList[T] { | |
def get(index: Int) = if (index == 0) value else next.get(index - 1) | |
def length = (1 + next.length) | |
override def toString = value.toString + " " + next.toString | |
} | |
var list: LinkedList[String] = new Empty[String]; | |
for (i <- 0 to 10) list = list.add(i.toString) | |
println(list) | |
println(list.length) | |
//------------------------ | |
class MutableList[T] { | |
var node:LinkedList[T] = new Empty[T] | |
def add(someV: T) = { node = node.add(someV) } | |
def length = node.length | |
override def toString = { | |
var cursor:LinkedList[T] = node | |
var buffer = "[" + cursor.get(0).toString | |
for (i <- 0 to (cursor.length - 1) ) | |
buffer += " " + cursor.get(i).toString | |
buffer += "]" | |
buffer | |
} | |
} | |
val mList = new MutableList[String] | |
for (i <- 0 to 10) mList.add(i.toString) | |
println(mList) | |
println(mList.length) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment