forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueueBasedOnLinkedList.swift
55 lines (44 loc) · 1.12 KB
/
QueueBasedOnLinkedList.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//
// 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
}
}