欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

40 - 用栈实现队列

程序员文章站 2022-07-15 12:14:41
...

2017.9.19

public class MyQueue {
   private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    public MyQueue() {
        // do intialization if necessary
    	stack1 = new Stack<Integer>();
    	stack2 = new Stack<Integer>();
    }

    /*
     * @param element: An integer
     * @return: nothing
     */
    public void push(int element) {
        // write your code here
    	while(!stack2.isEmpty()){
    		stack1.push(stack2.pop());
    	}
    	stack1.push(element);
    }

    /*
     * @return: An integer
     */
    public int pop() {
        // write your code here
    	while(!stack1.isEmpty()){
    		stack2.push(stack1.pop());
    	}
    	int x = stack2.pop();
    	while(!stack2.isEmpty()){
    		stack1.push(stack2.pop());
    	}
    	return x;
    }

    /*
     * @return: An integer
     */
    public int top() {
        // write your code here
    	while(!stack1.isEmpty()){
    		stack2.push(stack1.pop());
    	}
    	int x = stack2.peek();
    	while(!stack2.isEmpty()){
    		stack1.push(stack2.pop());
    	}
    	return x;
    }
}