/** * 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_02_Queue_Imp { enum QueueError: Error { case Empty case Full } struct Queue { class Cell { let content: Int var next: Cell? init (content: Int, next: Cell?) { self.content = content self.next = next } } static var queueHead: Cell? = nil static var queueEnd: Cell? = nil static func Enqueue(x: Int) { let newCellPtr = Cell(content: x, next: nil) if (queueHead == nil) { queueHead = newCellPtr queueEnd = newCellPtr } else { queueEnd?.next = newCellPtr queueEnd = newCellPtr } } static func Dequeue() throws -> Int { guard let firstCell = queueHead else { throw QueueError.Empty } if (firstCell.next == nil) { queueHead = nil queueEnd = nil } else { queueHead = queueHead?.next } return firstCell.content } } static func run() { for i in 1 ... 10 { Queue.Enqueue(x: i) } for _ in 1 ... 10 { do { try print(Queue.Dequeue()) } catch { print("Failed") } } } }