queue1 是最后生成的栈
queue2 是临时队列,把新进来的先放进去,再把queue1里的数据从头到尾读进去,然后互换
class MyStack { var queue1: [Int] = [] var queue2: [Int] = [] init() { } func push(_ x: Int) { queue2.append(x) while !queue1.isEmpty { queue2.append(queue1.removeFirst()) } swap(&queue1, &queue2) } func pop() -> Int { let r: Int = queue1.removeFirst() return r } func top() -> Int { var r: Int = 0 if !queue1.isEmpty { r = queue1.first! } return r } func empty() -> Bool { return queue1.isEmpty } } /** * Your MyStack object will be instantiated and called as such: * let obj = MyStack() * obj.push(x) * let ret_2: Int = obj.pop() * let ret_3: Int = obj.top() * let ret_4: Bool = obj.empty() */
https://leetcode.cn/problems/implement-stack-using-queues/
标签:Int,obj,队列,queue2,queue1,let,func,swift,Leetcode From: https://www.cnblogs.com/huangzs/p/17648807.html