Two stacks to implement the specific implementation code of the queue

queue

1. Problem solving ideas

  • First of all, use two stacks to implement the queue. It is necessary to understand that the stack is first in last out, and the queue is first in first out;
  • Then we use one of the stacks to implement the enqueue operation, and the other one is used to dequeue, that is, one only takes in and one only takes out;
  • For example, there is a set of numbers [12,23,45,55]; enter 12,23 into s1, and now you want to leave the team, the first one to go out should be 12, then you only need to add all of s1 to s2, In this way, just pop up;
  • If you want to leave the team, you should first check whether there are any elements in s2. If so, you only need to pop the elements; if you don’t put all the elements in s1 into s2 for popping;
    Insert picture description here

2. Realize

2.1 Enrollment operation
//入栈
    public void push(int x) {
    
    
        /*
        1.首先给s1入栈
         */
        s1.push(x);
    }

2.2 Dequeue operation
public int pop() {
    
    
        /*
        1.如果s2为空,则将s1全部的值先移动到s2
        2.如果s2有值,则直接弹出
         */
        if (s2.empty()){
    
    
            while(!s1.empty()){
    
    
                s2.push(s1.pop());
            }
        }
        if (!s2.empty()){
    
    
            return s2.pop();
        }
        return -1;
    }
2.3 Pop-up head element
public int peek() {
    
    
        if (s2.empty()){
    
    
            while(!s1.empty()){
    
    
                s2.push(s1.pop());
            }
        }
        if (!s2.empty()){
    
    
            return s2.peek();
        }
        return -1;

    }

2.4 Determine whether it is empty
public boolean empty() {
    
    
        if (s1.empty() && s2.empty()){
    
    
            return true;
        }
        return false;
    }

Guess you like

Origin blog.csdn.net/qq_45665172/article/details/110230048