面试题:用两个栈实现一个队列 Java语言实现

面试题:用两个栈实现一个队列 Java语言实现

分析

栈是先进后出,队列是先进先出,为了用两个栈实现一个队列的进和出方法,可以这样:
进:保存到栈一里面;底|1|2|3|
出:栈一中的元素依次出栈,并进入到栈二中 底|3|2|1|,然后再把栈二顶的元素推出,就
实现了队列的出功能;

Java代码实现

package cn.edu.ncu.java;

import java.util.Stack;

/** 栈是先进后出,队列是先进先出,为了用两个栈实现一个队列的进和出方法,可以这样:
 * 进:保存到栈一里面;底|1|2|3|
 * 出:栈一中的元素依次出栈,并进入到栈2中 底|3|2|1|,然后再把栈二顶的元素推出,就
 * 实现了队列的出功能;
 *
 */
//two stacks implement one queue
public class TestStackAndQueue {
    public static void main(String[] args) {
        MyQueue<Integer> myQueue = new MyQueue<>();
        //push into queue
        myQueue.push(1);
        myQueue.push(2);
        myQueue.push(3);

        //test pop
        System.out.println("队列出队的第" + "1" + "个是:" + myQueue.pop());
        System.out.println("队列出队的第" + "2" + "个是:" + myQueue.pop());
        System.out.println("队列出队的第" + "3" + "个是:" + myQueue.pop());
    }
}

class MyQueue<ElementType> {
    public MyQueue() {
    }
    private Stack<ElementType> stack1 = new Stack<>();
    private Stack<ElementType> stack2 = new Stack<>();
    //push : push to the first stack;
    public void push(ElementType e) {
        stack1.push(e);
    }
    //pop: first pop all the elements to the 2nd stack, then pop from the 2nd stack;
    public ElementType pop() {
        //from stack1 to stack2
        while (!stack1.empty()) {
            stack2.push(stack1.pop());
        }
        //pop out from stack2
        return stack2.pop();
    }
    public boolean isEmpty() {
        return stack1.empty();
    }
}

运行结果

在这里插入图片描述

发布了33 篇原创文章 · 获赞 13 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_38086836/article/details/105260376