Topic: Implementing queues with two stacks

Implement a queue with two stacks one queue. Implement appendTail and deleteHead to insert a node at the end of the queue and delete a node at the head of the queue, respectively.

Their thinking

First understand the characteristics of stack: fifo, queue: fifO; So, for every element in the queue, stack 1 pushes one element, and when the queue needs to push one element out, stack 1 pushes one element into stack 2, and then pops out of stack 2, so that you can implement fifO with two stacks.

The problem solving code


    Stack<Integer> stack1 = new Stack<>();
    Stack<Integer> stack2 = new Stack<>();

    public void appendTail(int node) {
        stack1.push(node);
    }

    public int deleteHead(a) {
        if (stack2.isEmpty()) {
            while(stack1.empty() ! =true) { stack2.push(stack1.pop()); }}if (stack2.empty() == true) {
            return -1;
        }

        return stack2.pop();
    }

Copy the code

Afterword.

From Finger of the Sword offter