Espada se refiere a la segunda pila de preguntas y la cola de oferta.

Apilar y poner en cola

Descripción del Título

Utilice dos pilas para implementar una cola y completar las operaciones Push y Pop de la cola. Los elementos de la cola son de tipo int.

El método uno usa c ++

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

    int pop() {
    
    
        if(stack2.empty()){
    
    
            while(!stack1.empty()){
    
    
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
         int ret = stack2.top();
        stack2.pop();
        return ret;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

Método dos usa java

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(stack1.empty()&&stack2.empty()){
    
    
            throw new RuntimeException("Queue is empty!");
        }
        if(stack2.empty()){
    
    
            while(!stack1.empty()){
    
    
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

Supongo que te gusta

Origin blog.csdn.net/as1490047935/article/details/110245258
Recomendado
Clasificación