栈模拟队列 队列模拟栈

代码如下:

PS:做了一些测试,目前没问题。有问题请指正。。。

template
   
   
    
    
class myQueue
{
private:
  stack
    
    
     
      push_stack;
  stack
     
     
      
       pop_stack;
public:
  myQueue(){}
  ~myQueue(){}
  bool empty() const{return push_stack.empty() && pop_stack.empty();}
  void push(const T &x);
  void pop();
  T front(); //front is not a const function !!!
};

template
      
      
       
       
void myQueue
       
       
         ::push(const T& x) { push_stack.push(x); } template 
        
          void myQueue 
         
           ::pop() { if(empty()) throw runtime_error("empty queue!!!"); if(pop_stack.empty()) { while(!push_stack.empty()) { T x = push_stack.top(); push_stack.pop(); if(push_stack.empty()) return; pop_stack.push(x); } } else { pop_stack.pop(); } } template 
          
            T myQueue 
           
             ::front() { if(empty()) throw runtime_error("empty queue!!!"); if(pop_stack.empty()) { while(!push_stack.empty()) { T x = push_stack.top(); push_stack.pop(); pop_stack.push(x); } } return pop_stack.top(); } 
            
           
          
         
       
      
      
     
     
    
    
   
   

template
   
   
    
    
class MyStack
{
private:
  queue
    
    
     
      queue1;
  queue
     
     
      
       queue2;
public:
  MyStack(){}
  ~MyStack(){}
  bool empty() const {return queue1.empty() && queue2.empty();}
  void push(const T & x);
  void pop();
  T top() ;
};
template
      
      
       
       
void MyStack
       
       
         ::push(const T &x) { //if both empty, both ok if(queue1.empty()) queue2.push(x); else queue1.push(x); } template 
        
          void MyStack 
         
           ::pop() { if(empty()) throw runtime_error("empty stack!!!"); if(queue1.empty()) queue1.swap(queue2); assert(!queue1.empty()&&queue2.empty()); while(!queue1.empty()) { T x = queue1.front(); queue1.pop(); if(queue1.empty()) return; queue2.push(x); } } template 
          
            T MyStack 
           
             ::top() { if(empty()) throw runtime_error("empty stack!!!"); if(queue1.empty()) queue1.swap(queue2); assert(!queue1.empty()&&queue2.empty()); T x; while(!queue1.empty()) { x = queue1.front(); queue2.push(x); queue1.pop(); } return x; } 
            
           
          
         
       
      
      
     
     
    
    
   
   


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值