添加 232.用栈实现队列 Swift版本

This commit is contained in:
qiuxuewei
2021-11-24 15:33:59 +08:00
parent e85fbba56a
commit 63ad545c64

View File

@ -349,6 +349,43 @@ MyQueue.prototype.empty = function() {
};
```
Swift
```swift
class MyQueue {
var stackIn = [Int]()
var stackOut = [Int]()
init() {}
/** Push element x to the back of queue. */
func push(_ x: Int) {
stackIn.append(x)
}
/** Removes the element from in front of queue and returns that element. */
func pop() -> Int {
if stackOut.isEmpty {
while !stackIn.isEmpty {
stackOut.append(stackIn.popLast()!)
}
}
return stackOut.popLast() ?? -1
}
/** Get the front element. */
func peek() -> Int {
let res = pop()
stackOut.append(res)
return res
}
/** Returns whether the queue is empty. */
func empty() -> Bool {
return stackIn.isEmpty && stackOut.isEmpty
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>