Implement Queue using Stacks

来源:互联网 发布:三国杀 姜维 知乎 编辑:程序博客网 时间:2024/05/17 13:11

题目链接

思路:
两个栈。当有输出的时候。如果B里有东西就pop.没有的话把所有A里面的东西拿出来放入B。所有的入队全部放在A里面。

import java.util.Stack;class MyQueue {    // Push element x to the back of queue.    Stack<Integer> stackA=new Stack<Integer>();    Stack<Integer> stackB=new Stack<Integer>();    boolean isOut=true;    public void push(int x) {        stackA.push(x);    }    // Removes the element from in front of queue.    public void pop() {        if(stackB.isEmpty())        {            while(!stackA.isEmpty())            {                stackB.push(stackA.pop());            }        }        stackB.pop();    }    // Get the front element.    public int peek() {          if(stackB.isEmpty())          {            while(!stackA.isEmpty())            {                stackB.push(stackA.pop());            }          }          return stackB.peek();    }    // Return whether the queue is empty.    public boolean empty() {        return stackA.isEmpty()&&stackB.isEmpty();    }}
0 0
原创粉丝点击