/** * 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_03_RandomAccessList { enum RAListError: Error { case noSuchElement case noSuchPosition } struct RaList { enum Cells : Equatable { case Nil indirect case Cell(v: Int, next: Cells) } static var head: Cells = .Nil static func lookUp(index: Int) throws -> Int { var i = 0 var pos = head while (i < index) { switch pos { case .Nil : break case .Cell(_, let next) : pos = next i = i + 1 } } if (i != index) { throw RAListError.noSuchElement } switch pos { case .Cell(let value, _) : return value case .Nil : throw RAListError.noSuchElement } } static func InsertAtPos(x: Int, index: Int) throws { var prev: Cells = .Nil var pos = head var i = 0 While: while (i < index) { switch pos { case .Nil : break While case .Cell(_, let next) : prev = pos pos = next i = i+1 } } if (pos == .Nil && i < index) { throw RAListError.noSuchPosition } switch prev { case .Nil : head = .Cell(v: x, next: pos) case .Cell(_, var n) : n = .Cell(v: x, next: pos) } } } static func run() { for x in 0 ... 10 { do { try RaList.InsertAtPos(x: 10 - x, index: 0) } catch { print("Failed write") } } for i in 0 ... 10 { do { let v = try RaList.lookUp(index: i) print("\(i) : \(v)") } catch { print("Failed read") } } } }