题目:两个栈实现队列,栈是先入后出,队列是先入先出,两个栈可以利用这个特点实现队列.
核心代码:
<pre><code>`class MyQueue {
var stackNew:[Int] = []
var stackOld:[Int] = []
func push(value:Int) {
stackNew.append(value)
}
func peek() -> Int? {
shiftStacks()
let value:Int? = stackOld.last
if value != nil {
stackOld.removeLast()
}
return value
}
private func shiftStacks() {
if stackOld.count == 0 {
while stackNew.count > 0 {
let value:Int = stackNew.last!
stackNew.removeLast()
stackOld.append(value)
}
}
}
}`</code></pre>
测试代码:
<pre><code>`var myQueue:MyQueue = MyQueue()
for i in 0...3 {
myQueue.push(value: i)
}
var topValue:Int? = myQueue.peek()
if topValue != nil {
print("FlyElephant---顶部数据:(topValue!)")
}
for i in 10...15 {
myQueue.push(value: i)
}
for i in 0...4 {
var topValue:Int? = myQueue.peek()
if topValue != nil {
print("FlyElephant---顶部数据:(topValue!)")
}
}`</code></pre>