package kapitel_04 /** * Beispiel aus * * - Algorithmen und Datenstrukturen für Dummies * - von Andreas Gogol-Döring und Thomas Letschert * - Verlag Wiley-VCH; Oktober 2019 * - Kapitel 4, Listen: Immer einer nach dem anderen * * @author A. Gogol-Döring, Th. Letschert */ object AuD_04_01_Stack_Imp_App extends App { object List_Stack { case class Cell(v: Int, next: Cell) var head: Cell = null def Push(x: Int): Unit = { head = Cell(x, head) } def Pop(): Int = { head match { case Cell(v, next) => head = next v } } } class Array_Stack(n: Int) { val a = new Array[Int](n) var top = 0 def Push(x: Int): Unit = if (top < n) { a(top) = x top = top + 1 } else throw new IllegalStateException def Pop(): Int = { if (top > 0) { top = top - 1 a(top) } else throw new IllegalStateException } } case class Stack[T]() { sealed abstract class TList case object Nil extends TList case class Cons(v: T, next: TList) extends TList var stackRep: TList = Nil def Push(x: T): Unit = { stackRep = Cons(x, stackRep) } def Pop(): T = stackRep match { case Cons(head, tail) => stackRep = tail head case Nil => throw new IllegalStateException() } } val stack = new Stack[Int] for (i <- 1 to 10) stack.Push(i) for (i <- 1 to 10) println(stack.Pop()) }