fork download
  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4.  
  5. #define MAX 100
  6.  
  7. template <typename T>
  8. class Stack {
  9. public:
  10. Stack(); //构造函数
  11. bool empty() const ; //判断S是否为空栈
  12. bool full() const; //判断栈S是否为满,
  13. ~Stack(); //将栈S清空
  14. int size() const; //求栈S的长度,即栈S中的元素的个数
  15. const T & top() const; //返回栈S的栈顶元素
  16. void push( const T &e ); //入栈操作,将数据元素e插入栈S的当前栈顶
  17. T & pop(); //出栈操作,删除栈S的栈顶元素,并返回其值
  18. private:
  19. // 补充
  20. T data[MAX];
  21. int cur;
  22. };
  23.  
  24. template <typename T>
  25. Stack<T>::Stack()
  26. {
  27. cur = 0;
  28. }
  29.  
  30. template <typename T>
  31. bool Stack<T>::empty() const
  32. {
  33. return cur == 0;
  34. }
  35.  
  36. template <typename T>
  37. bool Stack<T>::full() const
  38. {
  39. return cur >= MAX;
  40. }
  41.  
  42. template <typename T>
  43. Stack<T>::~Stack() {}
  44.  
  45. template <typename T>
  46. int Stack<T>::size() const { return cur; }
  47.  
  48. template <typename T>
  49. const T & Stack<T>::top() const
  50. {
  51. if (cur == 0) throw "stack is empty";
  52. return data[cur - 1];
  53. }
  54.  
  55. template <typename T>
  56. void Stack<T>::push( const T &e )
  57. {
  58. if (cur >= MAX) throw "stack is full";
  59. data[cur++] = e;
  60. }
  61.  
  62. template <typename T>
  63. T & Stack<T>::pop()
  64. {
  65. if (cur == 0) throw "stack is empty";
  66. return data[--cur];
  67. }
  68.  
  69. //测试的main函数
  70. int main() {
  71. Stack<char> sc; //stack of char
  72. Stack<int> si; //Stack of int
  73. char ch = ' ';
  74. // 不断输入字符到栈中,=结束
  75. while (ch != '=') {
  76. cin >> ch;
  77. if (ch == 'a')
  78. sc.push('A');
  79. sc.push(ch);
  80. }
  81. cout << "top=" << sc.top() << "size=" << sc.size() << endl;
  82. cout << "pop " << sc.pop() << endl;
  83. while (!sc.empty())
  84. cout << sc.pop()<< " ";
  85. cout << endl;
  86.  
  87. int x = 1;
  88. // 不断输入int到栈中,0结束
  89. while (x != 0) {
  90. cin >> x;
  91. if (x > 10)
  92. si.push(10000);
  93. si.push(x);
  94. }
  95. cout << "top=" << si.top() << "size=" << si.size() << endl;
  96. cout << "pop " << si.pop() << endl;
  97. while (!si.empty())
  98. cout << si.pop()<< "/";
  99. cout << endl;
  100.  
  101. return 0;
  102. }
Success #stdin #stdout 0s 4536KB
stdin
abc=
1 2 3 4 0
stdout
top==size=5
pop =
c b a A 
top=0size=5
pop 0
4/3/2/1/