[Offer] to prove safety 05 - queue using two stacks

Reconstruction of a binary tree

Time limit : 1秒
space constraints : 32768K
this question knowledge : 队列
Title Description :

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        
    }
    
    public int pop() {
    
    }
}

Analysis of ideas:

Operation of sequentially undergoes the following changes:

  1. Two stacks are empty

  2. -> stack1 not empty empty stack2

  3. -> stack1 empty stack2 not empty

  4. -> two stacks are not empty

Two stacks are empty

Two stacks are empty stack1=[] stack2=[] Steps
Drawing {1, 2} stack1=[2, 1] stack2=[] 2 * stack1.push
Pop stack1=[] stack2=[] return null

stack1 not empty stack2 empty

1 2 not empty empty stack1=[2, 1] stack2=[] Steps
Drawing {3, 4} stack1=[4, 3, 2, 1] stack2=[] 2 * stack1.push
Pop stack1=[] stack2=[2, 3, 4] 4 * stack1.pop
4 * stack2.push
return stack2.pop

stack1 empty stack2 not empty

1 2 not empty Empty stack1=[] stack2=[2, 3, 4] Steps
Drawing {5, 6} stack1=[6, 5] stack2=[2, 3, 4] 2 * stack1.push
Pop stack1=[] stack2=[3, 4] return stack2.pop

Two stack is not empty

Two stack is not empty stack1=[6, 5] stack2=[2, 3, 4] Steps
Drawing {7, 8} stack1=[8, 7, 6, 5] stack2=[2, 3, 4] 2 * stack1.push
Pop stack1=[6, 5] stack2=[3, 4] return stack2.pop

summary:

  1. Stack situation: always stack1.push
  2. The stack case:
    • stack2 empty: all the elements of the stack stack1 to stack2, then perform stack2.pop
    • stack2 not empty: stack2.pop

answer:

import java.util.Stack;

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() {
        // 若 stack2 为空:将所有 stack1 元素入栈到 stack2
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

Guess you like

Origin www.cnblogs.com/jianminglin/p/11291789.html