Pila de código leet 232 Utilice la pila para implementar la cola

Directorio de artículos

LA

problema

Inserte la descripción de la imagen aquí

solución

Código


/*
思路: 两个栈怎么模拟呢? 一个只能先进后出, 另外一个能下进,上出。 我们在code中逐步思考。

- 
- 
- - 
- - 
- 
*/


class MyQueue {
    
    
public:
   stack<int> in ,out;
   /** Initialize your data structure here. */
   MyQueue() {
    
    

   }
   
   /** Push element x to the back of queue. */
   void push(int x) {
    
    
       in.push(x);

   }
   
   /** Removes the element from in front of queue and returns that element. */
   int pop() {
    
    
       if(out.empty()){
    
    
           while(!in.empty()){
    
    
               int x = in.top();
               in.pop();
               out.push(x);
           }
       }
       
           int x = out.top();
           out.pop();
           return x;
       

   }
   
   /** Get the front element. */
   int peek() {
    
    
       if(out.empty()){
    
    
           while(!in.empty()){
    
    
               int x = in.top();
               in.pop();
               out.push(x);
           }
       }
       
           int x = out.top();
           return x;
       


       

   }
   
   /** Returns whether the queue is empty. */
   bool empty() {
    
    
       if(in.empty()&&out.empty()) return  true;
       else return false;

   }
};

/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/


Resumen y reflexión

  1. Preste atención a cómo usar pop, top, etc. La API aún no es familiar.

Supongo que te gusta

Origin blog.csdn.net/liupeng19970119/article/details/114254765
Recomendado
Clasificación