当前位置: 代码迷 >> 综合 >> 232. Implement Queue using Stacks(未完全掌握,待总结,多种方法)
  详细解决方案

232. Implement Queue using Stacks(未完全掌握,待总结,多种方法)

热度:37   发布时间:2023-11-20 23:32:00.0

方法一:

在这里插入图片描述
用两个栈,如图示
在这里插入图片描述

class MyQueue {
    private Stack<Integer> inStack;private Stack<Integer> outStack;private int front;/** Initialize your data structure here. */public MyQueue() {
    inStack = new Stack<>();outStack = new Stack<>();}/** Push element x to the back of queue. */public void push(int x) {
    if(inStack.isEmpty()){
    front =  x;}if(outStack.isEmpty()){
    while(!inStack.isEmpty()){
    int tmp = inStack.pop();outStack.push(tmp);}}inStack.push(x);while(!outStack.isEmpty()){
    inStack.push(outStack.pop());}}/** Removes the element from in front of queue and returns that element. */public int pop() {
    int out = inStack.pop();if(!inStack.isEmpty())front = inStack.peek(); return out;}/** Get the front element. */public int peek() {
    return front;}/** Returns whether the queue is empty. */public boolean empty() {
    return inStack.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();*/

方法二

入队只需调用Stack的push()方法
出队:
根据栈 LIFO 的特性,s1 中第一个压入的元素在栈底。为了弹出 s1 的栈底元素,我们得把 s1 中所有的元素全部弹出,再把它们压入到另一个栈 s2 中,这个操作会让元素的入栈顺序反转过来。通过这样的方式,s1 中栈底元素就变成了 s2 的栈顶元素,这样就可以直接从 s2 将它弹出了。一旦 s2 变空了,我们只需把 s1 中的元素再一次转移到 s2 就可以了。

private Stack<Integer> s1 = new Stack<>();
private Stack<Integer> s2 = new Stack<>();// Push element x to the back of queue.
public void push(int x) {
    if (s1.empty())front = x;s1.push(x);
}
// Removes the element from in front of queue.
public void pop() {
    if (s2.isEmpty()) {
    while (!s1.isEmpty())s2.push(s1.pop());}s2.pop();    
}// Return whether the queue is empty.
public boolean empty() {
    return s1.isEmpty() && s2.isEmpty();
}// Get the front element.
public int peek() {
    if (!s2.isEmpty()) {
    return s2.peek();}return front;
}