Leetcode232. 用栈实现队列

使用栈实现队列的下列操作:

  • push(x) – 将一个元素放入队列的尾部。
  • pop() – 从队列首部移除元素。
  • peek() – 返回队列首部的元素。
  • empty() – 返回队列是否为空。
    示例:

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 操作)。

解法:使用两个栈,

https://leetcode-cn.com/problems/implement-queue-using-stacks/solution/yong-zhan-shi-xian-dui-lie-by-leetcode/
题解里面介绍了两种方法,这里使用第二种方法,显然时间复杂度和空间复杂度都是O(N)

  • Java
class MyQueue {
   
    private int front;
    Stack<Integer> s1 = new Stack<>();
    Stack<Integer> s2 = new Stack<>();
    /** Initialize your data structure here. */
    public MyQueue() {
   
        
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
   
        if(s1.isEmpty()){
   
            front = x;
        }
        s1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
   
        if(s2.isEmpty()){
   
            while(!s1.isEmpty()){
   
                s2.push(s1.pop());
            }
        return s2.pop();
        }
        return s2.pop();
    }
    
    /** Get the front element. */
    public int peek() {
   
        if(!s1.isEmpty()){
   
            return front;
        }
        return s2.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
   
        return s1.isEmpty() && s2.isEmpty();
    }
}

/** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */
  • Python
class MyQueue:

    def __init__(self):
        """ Initialize your data structure here. """
        self.front = 0
        self.s1 = []
        self.s2 = []

    def push(self, x: int) -> None:
        """ Push element x to the back of queue. """
        if not self.s1:
            self.front = x
        self.s1.append(x)

    def pop(self) -> int:
        """ Removes the element from in front of queue and returns that element. """
        if not self.s2:
            while self.s1:
                self.s2.append(self.s1.pop())
            return self.s2.pop()
        return self.s2.pop()

    def peek(self) -> int:
        """ Get the front element. """
        if self.s1:
            return self.front
        return self.s2[-1]

    def empty(self) -> bool:
        """ Returns whether the queue is empty. """
        return not self.s1 and not self.s2


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

Leetcode225. 用队列实现栈

使用队列实现栈的下列操作:

  • push(x) – 元素 x 入栈

  • pop() – 移除栈顶元素

  • top() – 获取栈顶元素

  • empty() – 返回栈是否为空
    注意:

  • 你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。

  • 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

  • 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

解法:使用两个队列和一个队列的空间复杂度都是O(N),但是明显一个队列的内存占用会更少一些

https://leetcode-cn.com/problems/implement-stack-using-queues/solution/yong-dui-lie-shi-xian-zhan-by-leetcode/

  • Java
class MyStack {
   
    private Queue<Integer> q1 = new LinkedList<>();
    /** Initialize your data structure here. */
    public MyStack() {
   
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
   
        this.q1.add(x);
        int size = this.q1.size();
        while(size>1){
   
            this.q1.add(this.q1.remove());
            size--;
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
   
        return this.q1.remove();
    }
    
    /** Get the top element. */
    public int top() {
   
        return this.q1.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
   
        return this.q1.isEmpty();
    }
}

/** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * boolean param_4 = obj.empty(); */
  • Python
class MyStack:

    def __init__(self):
        """ Initialize your data structure here. """
        self.q1 = []
        

    def push(self, x: int) -> None:
        """ Push element x onto stack. """
        self.q1.append(x)
        length = len(self.q1)
        while length>1:
            self.q1.append(self.q1.pop(0))
            length -= 1
            

    def pop(self) -> int:
        """ Removes the element on top of the stack and returns that element. """
        return self.q1.pop(0)

    def top(self) -> int:
        """ Get the top element. """
        return self.q1[0]
        

    def empty(self) -> bool:
        """ Returns whether the stack is empty. """
        return not self.q1


# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()