232. 用栈实现队列 java实现 算法之路

232. 用栈实现队列

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

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

示例:

MyQueue queue = new MyQueue();

 

queue.push(1);

queue.push(2);  

queue.peek();  // 返回 1

queue.pop();   // 返回 1

queue.empty(); // 返回 false

解题思路:

栈是先进后出,而队列是先进先出。

所以需要用到两个栈来实现队列。

  1. 一个为输入栈(inputStack),即全部的输入内容放入该inputStack栈。一个输出栈(outputStack),即需要全部输出的内容放入该栈(l例如peek,pop)。
  2. 全部输入的内容由inputstack接收。
  3. 当需要输出的时候,即遇到pop,peek的时候,先查看outStack是否为空。为空就从inputStack获取数据。不为空直接输出
class MyQueue {
    /** Initialize your data structure here. */
    private Stack in;//输入栈
    private Stack out;//输出栈
    public MyQueue() {
        
        in = new Stack();
        out = new Stack();
        
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
          
        in.push(x);//全部输入由输入栈接收
       
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        //遇到pop操作,先判断out输出栈是否为空,
        if(out.empty()){
           while (!in.empty()){//为空,把输入栈in的内容push入输出栈
                out.push(in.pop());
           }
        }
        return out.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        //peek操作同pop
        if(out.empty()){
           while (!in.empty()){
                out.push(in.pop());
           }
          
        }
          return out.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        if(in.empty() && out.empty()){
            return true;
        }else
            return false;
    }
}
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        if(in.empty() && out.empty()){
            return true;
        }else
            return false;
    }
}

 

你可能感兴趣的:(java,算法)