/** * 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 */ import Foundation struct AuD_04_01_Stack_Imp { enum StackError: Error { case Empty case Full } struct List_Stack { enum Cells { case Nil indirect case Cell(v: Int, next: Cells) } static var head: Cells = .Nil static func Push(x: Int) { head = .Cell(v: x, next: head) } static func Pop() throws -> Int { switch head { case .Cell(let v, let next) : head = next return v case .Nil : throw StackError.Empty } } } class Array_Stack { let n: Int var a: [Int] var top = 0 init(size: Int) { n = size a = [Int](repeating: 0, count: n) } func Push(x: Int) throws { if (top < n) { a[top] = x top = top + 1 } else { throw StackError.Full } } func Pop() throws -> Int { if (top > 0) { top = top - 1 return a[top] } else { throw StackError.Empty } } } class Stack { enum TList { case Nil indirect case Cons(v: T, next: TList) } var stackRep: TList = .Nil func Push(x: T) { stackRep = .Cons(v: x, next: stackRep) } func Pop() throws -> T { switch stackRep { case .Cons(let head, let tail) : stackRep = tail return head case .Nil : throw StackError.Empty } } } static func run() throws { let stack: Stack = Stack() for i in 1 ... 10 { stack.Push(x: i) } for _ in 1 ... 10 { try print(stack.Pop()) } } }