(B) [Offer] [9] [queue with two stacks]

Title Description

  Two stacks queue
  

Ideas analysis

  1. Stack -> last-out queue -> FIFO
  2. Queues into operation, s1 selected stack into the stack, and implementation of the key -queue operation, taking into account the nature of the FIFO queue, to eject the elements s1 and s2 pushed onto the stack when the queue, then it popped s2 We can guarantee the nature of the FIFO. ## Java Code
public class Offer009 {
    public static void main(String[] args) {

    }

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

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

    public int pop() {
        if (stack2.isEmpty()) {
            if (stack1.isEmpty()) {
                throw new IllegalStateException("队列为空");
            } else {
                while (!stack1.isEmpty()) {
                    stack2.push(stack1.pop());
                }
            }
        }
        return stack2.pop();
    }
}

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/boffer9-yong-liang-ge-zhan-shi-xian-dui-lie.html