如何用栈实现队列?

问题出自:程序员小灰 - 如何用栈实现队列?

代码实现


import java.util.*;

public class DummyQueue {

    Stack stack1;

    Stack stack2;

    DummyQueue(){

        stack1 = new Stack();

        stack2 = new Stack();

    }

    public void offer(int num) {

        stack1.push(num);

    }

    public int peek() {

        if(!stack2.isEmpty()) {

            return stack2.peek();

        }

        dropStack();

        return stack2.peek();

    }

    public int pull() {

    if(!stack2.isEmpty()) {

        return stack2.pop();

    }    

    dropStack();

        return stack2.pop();

    }

    public void dropStack() {

        while(!stack1.isEmpty()) {

            stack2.push(stack1.pop());

        }

        return;

    }

    public static void main(String[] args) {

        DummyQueue queue = new DummyQueue();

        queue.offer(1);

        queue.offer(2);

        queue.offer(3);

        System.out.println(queue.peek());

        System.out.println(queue.pull());

        System.out.println(queue.pull());

        queue.offer(4);

        queue.offer(5);

        System.out.println(queue.pull());

        System.out.println(queue.pull());

        System.out.println(queue.pull());

        System.out.println(queue.pull());

    }

}

测试结果

如何用栈实现队列?_第1张图片
image

你可能感兴趣的:(如何用栈实现队列?)