forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.swift
More file actions
42 lines (35 loc) · 706 Bytes
/
Stack.swift
File metadata and controls
42 lines (35 loc) · 706 Bytes
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
/*
Last-in first-out stack (LIFO)
Push and pop are O(1) operations.
*/
public struct Stack<T> {
private var array = [T]()
public var isEmpty: Bool {
return array.isEmpty
}
public var count: Int {
return array.count
}
public mutating func push(element: T) {
array.append(element)
}
public mutating func pop() -> T? {
if isEmpty {
return nil
} else {
return array.removeLast()
}
}
public func peek() -> T? {
return array.last
}
}
extension Stack: SequenceType {
public func generate() -> AnyGenerator<T> {
var curr = self
return anyGenerator {
_ -> T? in
return curr.pop()
}
}
}