Prove safety Offer: stack implementation with two queues (java version)

Title Description

Two stacks to achieve a queue, the completion queue Push and Pop operations. Queue elements int.

analysis

With stack1 to install a special element, then direct stack1.pop certainly does not work, stack2 to the elements.
The rule is: as long as there are elements in it stack2 pop, if stack2 is empty, stack1 all elements satck2 poured in, say, only new element into the stack1, only the elements out from stack2.
In this way, we can guarantee every pop out from stack2 elements is the oldest element.

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    public void push(int node) {
        stack1.push(node);
    }
    public int pop() {
        if(stack1.empty()&&stack2.empty()){
            throw new RuntimeException("empty");
        }else if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }   
        return stack2.pop();
    }
}

Guess you like

Origin blog.csdn.net/qq_43165002/article/details/93715742