歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 棧的基本操作(C++)

棧的基本操作(C++)

日期:2017/3/1 10:06:15   编辑:Linux編程

棧的基本操作(C++)

  1. #include<iostream>
  2. #include<stdlib.h>
  3. using namespace std;
  4. template <class elemtype>
  5. class stack {
  6. public:
  7. virtual bool is_empty() const = 0;
  8. virtual void push(const elemtype &x) = 0;
  9. virtual elemtype pop() = 0;
  10. virtual elemtype top() const = 0;
  11. virtual ~stack() {}
  12. };
  13. template <class elemtype>
  14. class set_stack: public stack <elemtype> {
  15. private:
  16. elemtype *elem;
  17. int top_p;
  18. int max_size;
  19. void double_space();
  20. public:
  21. set_stack(int init_size = 10) {
  22. elem = new elemtype [init_size];
  23. max_size = init_size;
  24. top_p = -1;
  25. }
  26. ~set_stack() { delete[] elem; }
  27. bool is_empty() const { return top_p == -1; }
  28. void push(const elemtype &x) {
  29. if(top_p == max_size - 1) {
  30. double_space();
  31. }
  32. elem[++top_p] = x;
  33. }
  34. elemtype pop() {
  35. return elem[--top_p];
  36. }
  37. elemtype top() const {
  38. return elem[top_p];
  39. }
  40. };
  41. template <class elemtype>
  42. void set_stack<elemtype>::double_space(){
  43. elemtype *tmp = elem;
  44. elem = new elemtype[2*max_size];
  45. for(int i = 0; i < max_size; ++i) {
  46. elem[i] = tmp[i];
  47. }
  48. max_size *= 2;
  49. delete[] tmp;
  50. };
  51. int main()
  52. {
  53. set_stack<int> *s = new set_stack<int>(10);
  54. cout<<s->is_empty();
  55. // s->push(3);
  56. for(int i = 1; i <= 20; i++) {
  57. s->push(i*10);
  58. }
  59. for(int i = 1; i <=20 ; i++) {
  60. cout << s->top() << endl;
  61. s->pop();
  62. }
  63. cout<<s->top();
  64. return 0;
  65. }
  66. //這道題目的意義重大,標志我要全面學習C++了!呵呵,加油。
Copyright © Linux教程網 All Rights Reserved