两个栈实现队列

题目描述:

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

思路:

栈:先进后出

队列:先进先出

压入元素直接压入stack1

删除元素先查看stack2是否为空,非空则弹出;空则将stack1中元素取出,置于stack2中

代码:

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhubo
 * @description: 利用两个栈来实现队列功能
 * @time: 2018年04月26日
 * @modifytime:
 */
public class StackQueue
{
    Stack<Integer> stack1 = new Stack<>();
    Stack<Integer> stack2 = new Stack<>();

    public void push(Integer i){
        stack1.push(i);
    }
    public Integer pop(){
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){ // 重点:每次stack2取完之后,将所有stack1中所有的元素放到stack2中
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }

    public static void main(String[] args) {
        StackQueue sq = new StackQueue();
        sq.push(1);
        sq.push(2);
        sq.push(3);
        sq.push(4);
        System.out.println(sq.pop() + ":" + sq.pop() + ":" + sq.pop() + ":" + sq.pop());
    }
}

猜你喜欢

转载自my.oschina.net/LucasZhu/blog/1801904