Skip to content

Instantly share code, notes, and snippets.

@cooler333
Last active June 17, 2020 08:20
Show Gist options
  • Save cooler333/51bf78808f91a5ec130678c33da7e9c6 to your computer and use it in GitHub Desktop.
Save cooler333/51bf78808f91a5ec130678c33da7e9c6 to your computer and use it in GitHub Desktop.
import Foundation
class Object {
let identifier: String
init(identifier: String) {
self.identifier = identifier
}
}
protocol MutableCollectionProtocol {
var isEmpty: Bool { get }
func push(_ some: Object)
func pop() -> Object?
}
// First In Last Out
class Stack: MutableCollectionProtocol {
private var array = [Object]()
var isEmpty: Bool { return array.isEmpty }
func push(_ some: Object) {
array.append(some)
}
func pop() -> Object? {
return array.popLast()
}
}
// First In First Out
class Queue: MutableCollectionProtocol {
private var s1 = Stack()
private var s2 = Stack()
var isEmpty: Bool { fatalError() }
func push(_ some: Object) {
fatalError()
}
func pop() -> Object? {
fatalError()
}
}
var stack = Stack()
stack.push(Object(identifier: "1"))
stack.push(Object(identifier: "2"))
stack.push(Object(identifier: "3"))
// var queue = Queue()
// queue.push(Object(identifier: "1"))
// queue.push(Object(identifier: "2"))
// queue.push(Object(identifier: "3"))
let some: MutableCollectionProtocol = stack
let id1 = some.pop()?.identifier
print(id1)
let id2 = some.pop()?.identifier
print(id2)
// queue.push(Object(identifier: "4"))
// let id4 = some.pop()?.identifier
// print(id4)
let id3 = some.pop()?.identifier
print(id3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment