常见面试题-用两个栈实现一个队列

    xiaoxiao2024-10-26  84

    栈:先进后出 队列:先进先出

    一个简单实现: 分两个操作:入队 、 出队

    s1用来入队s2用来出队 Stack<Integer> s1 = new Stack<>(); Stack<Integer> s2 = new Stack<>(); //入队 -> s1 s1.push(1); s1.push(2); s1.push(3); //出队 s2 if(s2.isEmpty()){ while (!s1.isEmpty()){ s2.push(s1.pop()); } System.out.println(s2.pop()); }else { System.out.println(s2.pop()); }

    拓展:用两个队列实现一个栈

    分两个操作:压栈、出栈

    压栈到q1从q2出栈 //用两个队列实现一个栈 Queue<Integer> q1 = new ArrayDeque<>(); Queue<Integer> q2 = new ArrayDeque<>(); //压栈 q1 q1.add(3); q1.add(2); q1.add(1); //出栈 if (q2.isEmpty()){ while (!q1.isEmpty()){ q2.add(q1.poll()); } System.out.println(q2.poll()); }else { System.out.println(q2.poll()); }

    参考: https://blog.csdn.net/smx_dd/article/details/80427788

    最新回复(0)