Interview questions to prove safety offer 9 (java version): two queue stacks

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/littlehaes/article/details/91384541

welcome to my blog

Interview questions to prove safety offer 9 (java version): two queue stacks

Title Description

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

Thinking

  • Create two stacks stack1, stack2
  • stack1 only responsible for adding elements
  • stack2 only responsible for removing elements; when stack2 not empty directly pop () to the top element, when stack2 is empty, the elements in the first stack1 pushed stack2, then pop () the top element

the complexity

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() {
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
            return stack2.pop();
        }
        else{
            return stack2.pop();
        }
    }
}

Guess you like

Origin blog.csdn.net/littlehaes/article/details/91384541