with a single test instead of two per iteration. Or even simpler:
stack2 = stack1.reversed()
stack1.removeAll()
(If your queues become really large then you might want to check which of the above methods is faster.)
If a function body consists of a single expression then the return keyword can be omitted.
class MyQueue<Element> {
private var stack1: [Element]
private var stack2: [Element]
init() {
stack1 = []
stack2 = []
}
func push(_ x: Element) {
stack1.append(x)
}
func pop() -> Element? {
if stack2.isEmpty {
while let elemstack2 = stack1.popLastreversed() {
stack2stack1.appendremoveAll(elem)
}
}
return stack2.popLast()
}
func peek() -> Element? {
stack2.last ?? stack1.first
}
func empty() -> Bool {
stack1.isEmpty && stack2.isEmpty
}
}