高薪算法+计算机职称考试LeetCodeSwift in LeetCode

LeetCode 232. 用栈实现队列 Implement Q

2019-07-27  本文已影响3人  1江春水

【题目描述】
使用栈实现队列的下列操作:

【示例】

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);  
queue.peek();  // 返回 1
queue.pop();   // 返回 1
queue.empty(); // 返回 false

【说明】

你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。

思路:使用双栈的原因是能通过b栈将原a栈的数据倒置,看书去吧!

代码实现:

栈-数据结构
struct Stack {
    fileprivate var arr = [Int]()
    mutating func pop() -> Int {
        return self.arr.removeLast()
    }
    mutating func push(_ num:Int) {
        self.arr.append(num)
    }
    func isEmpty() -> Bool {
        return self.arr.isEmpty
    }
    func peek() -> Int? {
        return self.arr.last
    }
}

class MyQueue {
    var stack1 = Stack.init()
    var stack2 = Stack.init()
    var first : Int?
    
    /** Initialize your data structure here. */
    init() {
        
    }
    
    /** Push element x to the back of queue. */
    func push(_ x: Int) {
        if stack1.isEmpty() {
            first = x
        }
        self.stack1.push(x)
    }
    
    /** Removes the element from in front of queue and returns that element. */
    func pop() -> Int {
        if stack2.isEmpty() {
            while !self.stack1.isEmpty() {
                let tmp = self.stack1.pop()
                self.stack2.push(tmp)
            }
        }
        return self.stack2.pop()
    }
    
    /** Get the front element. */
    func peek() -> Int { 
        return self.stack2.peek() ?? first!
    }
    
    /** Returns whether the queue is empty. */
    func empty() -> Bool {
         return stack1.isEmpty() && stack2.isEmpty()
    }
}
上一篇 下一篇

猜你喜欢

热点阅读