【剑指Offer】5、用两个栈实现队列

  题目描述:

  用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

  解题思路:

  本题的基本意图是:用两个后入先出的栈来实现先入先出的队列。对于这个问题,我们可以通过一个实例来进行具体分析。不难得出相应的规律:有两个栈stack1和stack2,每次向队列中插入元素可以都压入到stack1中,当需要从队列中删除元素时,我们应该是删除最早插入的那个(FIFO),这时可以将stack1中的元素逐个弹出并压入stack2,直到stack1为空,这时最早插入的元素就位于stack2的栈顶,可以直接弹出。

  因此,我们总结如下:压入元素时,都压入栈1,当需要弹出时,从栈2弹出,当栈2不为空时直接弹出栈顶元素,为空时将栈1的元素“倒进去”。

  举例:

  编程实现(Java):

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
   
    public void push(int node) {
        stack1.push(node);
    }
    
    public int pop() {
        if(stack2.empty()){  //为空时将栈1的元素“倒进去”
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

  扩展:用两个队列实现一个栈

  用两个队列实现栈相比稍微复杂,当插入一个元素时,可以选择不为空的那个队列直接加进去,而当删除一个元素时,需要借助另一个空队列,首先依次删除原队列的头,并将删除的元素加入另一个队列,直到找到队列最后一个元素,将其删除,这时原来的数据队列变空,另一个队列变为数据栈。

class MyStack {
    Queue<Integer> q1,q2;
    int topValue;

    /** Initialize your data structure here. */
    public MyStack() {
        q1=new LinkedList<>();
        q2=new LinkedList<>();
        topValue=0;
    }
    
    /** Push element x onto stack. */
    public void push(int x) {  //压入到不为空的那个队列中
        if(!q1.isEmpty())  
            q1.add(x);
        else
            q2.add(x);
        
        topValue=x;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        
        int temp=0;
        while(!q1.isEmpty()){  //q1不空
            temp=q1.poll();
            if(q1.isEmpty())
                return temp;
            q2.add(temp);
            topValue=temp;
        }
        while(!q2.isEmpty()){  //q1不空
            temp=q2.poll();
            if(!q2.isEmpty()){
                q1.add(temp);
                topValue=temp;
            }
        }
        return temp;
    }
    
    /** Get the top element. */
    public int top() {
        return topValue;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return q1.isEmpty() && q2.isEmpty();
    }
}
原文地址:https://www.cnblogs.com/gzshan/p/10730367.html