剑指offer面试题7:用两个栈实现队列

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

代码实现:

public class Solution07
{
    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.isEmpty())
            return stack2.pop();
        else
        {
            while(!stack1.isEmpty())
                stack2.push(stack1.pop());
        }
        return stack2.pop();
    }
}

题目2:用两个队列实现一个栈,代码实现:

public class Solution07_01
{
    Deque<Integer> deque1=new ArrayDeque<>();
    Deque<Integer> deque2=new ArrayDeque<>();
    
    public void push(int node)
    {
        if(deque2.isEmpty())
            deque1.push(node);
        else
            deque2.push(node);
    }
    public int pop() throws Exception
    {
        if(!deque2.isEmpty())
        {
            while(deque2.size()>1)
            {
                deque1.push(deque2.pop());
            }
            return deque2.pop();
        }
        else if(!deque1.isEmpty())
        {
            while(deque1.size()>1)
            {
                deque2.push(deque1.pop());
            }
            return deque2.pop();
        }
        else
            throw new Exception("null");
    }
}
原文地址:https://www.cnblogs.com/xujian2014/p/5475685.html