232. 用栈实现队列

题目链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/

执行用时:0 ms, 在所有 Swift 提交中击败了100.00%的用户
内存消耗:13.7 MB, 在所有 Swift 提交中击败了92.41%的用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class MyQueue {
var front = 0
var inStack = [Int]()
var outStack = [Int]()
init() {
front = 0
inStack = []
outStack = []
}

func push(_ x: Int) {
if inStack.isEmpty {
front = x
}
inStack.append(x)
}

func pop() -> Int {
if outStack.isEmpty {
while !inStack.isEmpty {
outStack.append(inStack.removeLast())
}
}
return outStack.removeLast()
}

func peek() -> Int {
if !outStack.isEmpty {
return outStack.last!
}
return front
}

func empty() -> Bool {
return inStack.isEmpty && outStack.isEmpty
}
}

232. 用栈实现队列
https://pisces34.github.io/2021/10/01/leetcode/232copy/
发布于
2021年10月1日
许可协议