stack(using queue)

这道题是利用了两个queue实现stack的基本功能, 较难的地方在于pop
与用map实现multiset有相像之处
难点在于pop,pop也体现了本题用两个queue而不是一个的原因
下面是实现的代码

class Stack {
  public:
    Stack() {
      count = 0;
    }
    void push(const T& data) {
      q1.push(data);
      count++;
    }
    T pop() {
      if (!empty()) {
      int n = count;
      for (int i = 0; i < n; i++) {
        q2.push(q1.front());
        q1.pop();
      }
      for (int i = 0; i < n - 1; i++) {
        q1.push(q2.front());
        q2.pop();
      }
      T temp = q2.front();
      q2.pop();
      count--;
      return temp;
      }
      return -1;
    }// return the value in the top and pop it out of the stack.
    T top() {
      return q1.back();
    } // return the value in top.
    int size() const {
      return count;
    }
    bool empty() {
      return count == 0;
    }

  private:
    queue<T> q1;
    queue<T> q2;
    int count; // the number of elements.
};
template<typename T>
void print(Stack<T>& a) {
  T temp[100];
  int n = a.size();
  for (int i = 0; i < n; ++i) {
    cout << a.top() << " ";
    temp[i] = a.top();
    a.pop();
  }
  cout << endl;
  for (int i = n - 1; i >= 0; --i) {
    a.push(temp[i]);
  }
}

(1)pop:
先将q1中的元素从队头开始入q2,此时q2中的元素与q1中的元素一样,每一次push的同时,q1.pop(); 在将q2中的元素从队头开始重新入q1,最后一个元素不要push,从而实现删除掉最后一个元素的目的,即栈后进先出的特点.

(2)
注意在print函数中不能改变实参,所以要先把传进去的栈的内容先存起

下面是测试函数:

class StackForbidden : public exception {
    virtual const char *what() const throw() {
        return "Please do not use Stack in stl..";
    }
};

int main() {
  #if defined(_GLIBCXX_STACK)
    throw StackForbidden();
#endif

Stack<int> stack;
stack.push(88);
stack.push(44);
stack.push(99);

cout << "The size is: " << stack.size() << endl;
if (!stack.empty()) cout << stack.top() << endl;
print(stack);

stack.pop();
print(stack);

stack.push(777);
cout << "The size is: " << stack.size() << endl;
if (!stack.empty()) cout << stack.top() << endl;
print(stack);

stack.pop();
stack.pop();
cout << "The size is: " << stack.size() << endl;
print(stack);
stack.pop();
if (!stack.empty()) cout << stack.top() << endl;
else cout << "it is empty now." << endl;

Stack<double> stack1;
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
    stack1.push(i + 0.01);
}
print(stack1);
while (m--) {
    stack1.pop();
}
cout << "The size is: " << stack1.size() << endl;
if (!stack1.empty()) cout << stack1.top() << endl;
print(stack1);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值