5、剑指offer之用两个栈实现队列,题目解析和java实现方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AustinBoris/article/details/79844808

题目描述


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

要求

时间限制:1秒 空间限制:32768K

实现思路

首先我们回顾一下队列和栈的区别

  • 队列是先进先出的数据结构
  • 栈是先进后出的数据结构

首先我们来考虑一下队列的进队操作,这个和栈的进栈操作一致,故可以利用栈1进行进栈操作。
至于出队的操作则需要另外一番操作,这时可以利用另外一个栈(栈2)来缓存队列中的数据。操作如下:

  1. 将栈1的数据依次出栈,赋值为temp,然后将temp压入栈2,循环直至栈1清空。
  2. 栈2弹出栈顶元素。
  3. 将栈2的数据依次出栈,复制为temp,然后将temp压入栈1,循环直至栈2清空。

当然,在进行进出栈操作时,需要判断栈1或栈2是否为空对象或者,是否为空栈。

代码实现

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() {
        int result = 0;
        while(stack1.empty()==false){
            Integer temp = stack1.pop();
            stack2.push(temp);
            continue;
        }
        if(stack2.empty()==false){
            result = stack2.pop();
            while(stack2.empty()==false){
                Integer temp = stack2.pop();
                stack1.push(temp);
                continue;
            }
        }
        return (int)result;
    }
}

猜你喜欢

转载自blog.csdn.net/AustinBoris/article/details/79844808