用两个栈实现一个队列

import java.util.Scanner;
import java.util.Stack;

public class test25 {
    public static void main(String[] args) {
        MyQueue<Integer> myQueue = new MyQueue<>();
        Scanner sc = new Scanner(System.in);
        int choice;
        while(true) {
            System.out.println("请选择操作:1.入队;2.出队;3.退出");
            choice = sc.nextInt();
            if(choice == 1) {
                int input = sc.nextInt();
                myQueue.queuePush(input);
            } else if(choice == 2) {
                if(myQueue.queuePop() != null) {
                    System.out.println((int)myQueue.queuePop());
                }
            } else {
                return;
            }
        }
    }
    static class MyQueue<E> {
        Stack<E> stack1;
        Stack<E> stack2;
        public MyQueue() {
            stack1 = new Stack<>();
            stack2 = new Stack<>();
        }
        public void queuePush(E e) {
            while(!stack2.isEmpty()) {
                stack1.push(stack2.pop());
            }
            stack1.push(e);

        }
        public <E> E queuePop() {
            if(stack1.isEmpty() && stack2.isEmpty()) {
                System.out.println("空队列");
                return null;
            }
            while(!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
            return (E)stack2.pop();
        }
    }
}

posted @ 2021-08-26 10:11  又又又8  阅读(33)  评论(0编辑  收藏  举报