Realize Queue with Two Stacks-Java Realization

Implement the queue with two stacks

Fortunately, I beat 80% in one pass

Problem solution (using Niuke's problem-solving ideas)

1. Analysis

The characteristic of the queue is: "first in, first out", and the characteristic of the stack is: "first in, first out"

When we insert the numbers a, b, and c into the simulated queue, assuming stack1 is inserted, the stack situation at this time is:

  • Stack stack1: {a,b,c}
  • Stack stack2: {}

When a number needs to be ejected, according to the "first in, first out" principle of the queue, if a enters first, then a should be ejected first. But now a is at the bottom of stack1, pop all the elements in stack1 into stack2 one by one, and now you can pop a from stack2 correctly. The stack situation at this time is:

  • Stack stack1: {}
  • Stack stack2: {c,b}

Continue to pop a number, b enters the "queue" before c, and b pops out. Note that b is at the top of stack2 and can be popped directly. The stack situation at this time is:

  • Stack stack1: {}
  • Stack stack2: {c}

At this time, insert a number d into the simulation queue, or insert stack1. The stack situation at this time is:

  • Stack stack1: {d}
  • Stack stack2: {c}

Pop a number, c is entered before d, c is popped, note that c is at the top of stack2 and can be popped directly. The stack situation at this time is:

  • Stack stack1: {d}
  • Stack stack2: {c}

According to the above chestnuts, conclusions can be drawn:

  1. When inserting, insert directly into stack1
  2. When popping, when stack2 is not empty, pop the top element of stack2, if stack2 is empty, pop all the numbers in stack1 into stack2 one by one, and then pop the top element of stack2

method one

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.empty()){
    
    
            while(!stack1.empty()){
    
    
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}
the complexity:

Push time complexity: O(1)
pop space complexity: O(1)

Guess you like

Origin blog.csdn.net/weixin_43957211/article/details/114588573