mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 232.用栈实现队列 Swift版本
This commit is contained in:
@ -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>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user