zl程序教程

您现在的位置是:首页 >  其他

当前栏目

栈模拟队列 队列模拟栈

2023-09-27 14:27:22 时间

代码例如以下:

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