C++ 指针堆栈

stcktp.h

  1. #ifndef PRO1_STCKTP_H
  2. #define PRO1_STCKTP_H
  3. template <class Type>
  4. class Stack {
  5. private:
  6. enum {SIZE = 10};
  7. int stacksize;
  8. Type * items;
  9. int top;
  10. public:
  11. explicit Stack(int ss = SIZE);
  12. Stack(const Stack& st);
  13. ~Stack(){delete [] items;};
  14. bool isempty(){ return top == 0; }
  15. bool isfull(){ return top == stacksize;}
  16. bool push(const Type & item);
  17. bool pop(Type & item);
  18. Stack &operator=(const Stack & st);
  19. };
  20. template <class Type>
  21. Stack<Type>::Stack(int ss) :stacksize(ss), top(0){ items = new Type[stacksize]; }
  22. template <class Type>
  23. Stack<Type>::Stack(const Stack &st) {
  24. stacksize = st.stacksize;
  25. top = st.top;
  26. items = new Type[stacksize];
  27. for(int i = 0; i < top; i++)
  28. items[i] = st.items[i];
  29. }
  30. template <class Type>
  31. bool Stack<Type>::push(const Type &item) {
  32. if (top < stacksize) {
  33. items[top++] = item;
  34. return true;
  35. } else
  36. return false;
  37. }
  38. template <class Type>
  39. bool Stack<Type>::pop(Type &item) {
  40. if (top > 0) {
  41. item = items[--top];
  42. return true;
  43. } else
  44. return false;
  45. }
  46. template <class Type>
  47. Stack<Type>& Stack<Type>::operator=(const Stack<Type> &st) {
  48. if (this == &st) {
  49. return *this;
  50. }
  51. delete [] items;
  52. stacksize = st.stacksize;
  53. top = st.top;
  54. items = new Type[stacksize];
  55. for (int i = 0; i < top; i++)
  56. items[i] = st.items[i];
  57. return *this;
  58. }
  59. #endif //PRO1_STCKTP_H

stcktp.cpp

  1. #include "stcktp.h"

main.cpp

  1. #include <iostream>
  2. #include "module11_class_template/pointer_stack/stcktp.h"
  3. using namespace std;
  4. // 正确使用指针堆栈
  5. const int Num = 10;
  6. void usePointerStack(){
  7. srand(time(0));
  8. cout << "Please enter stack size: ";
  9. int stacksize;
  10. cin >> stacksize;
  11. Stack<const char *> st(stacksize);
  12. const char * in[Num] = {
  13. "1:Hank Gilgamesh", "2:Kiki Ishtar", "3:Betty Rocker", "4:Ian Flagranti",
  14. "5:Wolfgang Kibble", "6:Portia Koop", "7:Joy Almonda", "8:Xaverie Paprika",
  15. "9:Juan Moore", "10:Misha Mache"
  16. };
  17. const char * out[Num];
  18. int processed = 0;
  19. int nextin = 0;
  20. while (processed < Num) {
  21. if (st.isempty()) {
  22. st.push(in[nextin++]);
  23. } else if(st.isfull())
  24. st.pop(out[processed++]);
  25. else if (rand()%2 && nextin < Num)
  26. st.push(in[nextin++]);
  27. else
  28. st.pop(out[processed++]);
  29. for (int i = 0; i < Num; i++)
  30. cout << out[i] << endl;
  31. cout << "Bye\n";
  32. }
  33. }
  34. int main() {
  35. usePointerStack();
  36. return 0;
  37. }