Skip to content

Instantly share code, notes, and snippets.

@BrandonShega
Last active March 27, 2017 20:03
Show Gist options
  • Save BrandonShega/fca4c5c8b5649bade4d272a48c8fc934 to your computer and use it in GitHub Desktop.
Save BrandonShega/fca4c5c8b5649bade4d272a48c8fc934 to your computer and use it in GitHub Desktop.
Queue with two stacks
var queue = Queue<String>()
queue.enqueue("Hello")
queue.enqueue("World")
queue.dequeue() // "Hello"
queue.dequeue() // "World"
queue.dequeue() // nil
struct Queue<T> {
var stack1 = Stack<T>()
var stack2 = Stack<T>()
mutating func enqueue(_ element: T) {
stack1.push(element)
}
mutating func dequeue() -> T? {
moveElements()
return stack2.pop()
}
var isEmpty: Bool {
return stack1.isEmpty && stack2.isEmpty
}
mutating func peek() -> T? {
moveElements()
return stack2.peek()
}
private mutating func moveElements() {
guard stack2.isEmpty else { return }
while let element = stack1.pop() {
stack2.push(element)
}
}
}
struct Stack<T> {
var elements: [T] = []
mutating func push(_ element: T) {
elements.append(element)
}
mutating func pop() -> T? {
return elements.popLast()
}
func peek() -> T? {
return elements.last
}
func isEmpty: Bool {
return elements.count == 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment