Advertisement
wendy890711

堆疊 佇列

May 27th, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. // ConsoleApplication2.cpp : 定義主控台應用程式的進入點。
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6. using namespace std;
  7.  
  8. template<class T, int MaxSize = 20>
  9. class Stack
  10. {
  11. public:
  12. void init(){ sp = 0, sp2 = 0; }
  13. void push(T data);
  14. T pop();
  15. private:
  16. int sp, sp2;
  17. T buffer[MaxSize];
  18. static void Error(){ cout << "\nStack Error\n"; }
  19. };
  20.  
  21. template < class T, int MaxSize>
  22. void Stack<T, MaxSize>::push(T data)
  23. {
  24. if (sp == MaxSize)
  25. Error();
  26. else
  27. buffer[sp++] = data;
  28. }
  29.  
  30.  
  31. template<class T,int MaxSize>
  32. T Stack<T, MaxSize>::pop()
  33. {
  34. if (sp == 0)
  35. {
  36. Error();
  37. return 0;
  38. }
  39. return buffer[--sp];
  40. }
  41.  
  42. template<class T, int MaxSize = 20>
  43. class Queue
  44. {
  45. public:
  46. void init(){ sp = 0, sp2 = 0; }
  47. void push(T data);
  48. T pop();
  49. private:
  50. int sp, sp2;
  51. T buffer[MaxSize];
  52. static void Error(){ cout << "\nStack Error\n"; }
  53. };
  54.  
  55. template < class T, int MaxSize>
  56. void Queue<T, MaxSize>::push(T data)
  57. {
  58. if (sp == MaxSize)
  59. Error();
  60. else
  61. buffer[sp++] = data;
  62. }
  63.  
  64. template<class T, int MaxSize>
  65. T Queue<T, MaxSize>::pop()
  66. {
  67. if (sp2 == sp)
  68. {
  69. Error();
  70. return 0;
  71. }
  72. return buffer[sp2++];
  73. }
  74.  
  75. int main()
  76. {
  77. Queue<int> st1;
  78. Queue<char, 10> st2;
  79. st1.init();
  80. st2.init();
  81.  
  82. st1.push(1); st1.push(2); st1.push(3);
  83. st2.push('a'); st2.push('b'); st2.push('c');
  84.  
  85. cout << st1.pop();
  86. cout << st2.pop();
  87. cout << st1.pop();
  88. cout << st2.pop();
  89. cout << st1.pop();
  90. cout << st2.pop();
  91. cout << st1.pop();
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement