algo/swift/09_queue/QueueBasedOnLinkedList.swift
Jiandan e121c388d3 [swift][09_queue][remove] Remove "typealias Element = T".
[swift][09_queue][fix] Fix "size" in "QueueBasedOnLinkedList".
2018-10-13 14:50:22 +08:00

56 lines
1.1 KiB
Swift

//
// Created by Jiandan on 2018/10/11.
// Copyright (c) 2018 Jiandan. All rights reserved.
//
import Foundation
struct QueueBasedOnLinkedList<Element>: Queue {
///
var head: Node<Element>?
///
var tail: Node<Element>?
// MARK: Protocol: Queue
var isEmpty: Bool { return head == nil }
var size: Int {
if isEmpty {
return 0
}
var count = 1 // head
while head?.next != nil {
count += 1
}
return count
}
var peek: Element? { return head?.value }
mutating func enqueue(newElement: Element) -> Bool {
if isEmpty {
//
let node = Node(value: newElement)
head = node
tail = node
} else {
tail!.next = Node(value: newElement)
tail = tail!.next
}
return true
}
mutating func dequeue() -> Element? {
if isEmpty {
return nil
}
let node = head
head = head!.next
return node?.value
}
}