码迷,mamicode.com
首页 > 其他好文 > 详细

栈模拟队列 队列模拟栈

时间:2019-03-29 13:15:10      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:oid   wap   error   代码   css   ref   cpp   sheet   template   

代码例如以下:

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;
}


栈模拟队列 队列模拟栈

标签:oid   wap   error   代码   css   ref   cpp   sheet   template   

原文地址:https://www.cnblogs.com/mqxnongmin/p/10620516.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
分享档案
周排行
mamicode.com排行更多图片
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!