经典面试题(七)

17 篇文章 0 订阅
12 篇文章 0 订阅

利用两个栈来实现队列的操作。

代码如下所示

#include <iostream>
#include <stack>
using namespace std;

template<class T>
class QueueFromStack{
private:
        stack<T> s1;
        stack<T> s2;
public:
       // use reference instead of variable pass
       void push(const T& value);
       T pop();
};
template<class T>
void QueueFromStack<T>:: push(const T& value){
  s1.push(value);
}
template<class T>
T QueueFromStack<T>:: pop(){
  if(!s2.empty()){
    T tmp = s2.top();
    s2.pop();
    return tmp;
  }else if( !s1.empty() ){
    while(!s1.empty()){
      s2.push(s1.top());
      s1.pop();
    }
    T tmp = s2.top();
    s2.pop();
    return tmp;
  }else // this is very important
    throw new exception();
}

int main(){
    int array[10]={1,2,3,4,5,6,7,8,9,0};
    QueueFromStack<int> *queue = new QueueFromStack<int>();
    for(int i = 0 ; i < 10; ++i){
      queue->push(array[i]);
    }
    for(int i = 0 ; i < 10; ++i){
      cout<<queue->pop()<<" ";
    }
    cout<<endl;
    delete queue;
    system("PAUSE");
    return 0;
}  

利用两个队列来实现栈的操作

#include <iostream>
#include <queue>
using namespace std;

template<class T>
class StackFromQueue{
private:
        queue<T> q1;
        queue<T> q2;
        T pop(queue<T>& q1, queue<T>& q2);
public:
       void push(const T& value);
       T pop();
};

template<class T>
T StackFromQueue<T>::pop(queue<T>& q1, queue<T>& q2){
  while(1!=q2.size()){
      q1.push(q2.front());
      q2.pop();
  }
  T tmp = q2.front();
  q2.pop();
  return tmp; 
}

template<class T>
void StackFromQueue<T>::push(const T& value){
  if(!q1.empty())
    q1.push(value);
  else 
    q2.push(value);
}

template<class T>
T StackFromQueue<T>::pop(){
  if(q1.empty() && q2.empty())
    throw new exception();
  if(q1.empty())
    return pop(q1,q2);
  else
    return pop(q2,q1);
}

int main(){
    StackFromQueue<int> stack;
    for(int i = 0 ; i < 10; ++i)
      stack.push(i);
    for(int i = 0 ; i < 10 ; ++i)
      cout<<stack.pop()<<" ";
    cout<<endl;
    system("PAUSE");
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值