[关闭]
@qiezhian 2014-11-15T08:44:48.000000Z 字数 1202 阅读 1024

简单栈的实现

programming


  1. /*
  2. Filename: stack.h
  3. Function: Implemention of stack that can compatible with some
  4. basic data types like int,char even some custom class
  5. Details:
  6. */
  7. #include <iostream>
  8. #define MAXNUM 10
  9. using namespace std;
  10. template<class Item>
  11. struct StackNode
  12. {
  13. Item s[MAXNUM];
  14. StackNode* next;
  15. };
  16. template<class Item>
  17. class MyStack
  18. {
  19. private:
  20. StackNode<Item>* head;
  21. int top;
  22. public:
  23. MyStack();
  24. ~MyStack();
  25. Item Pop();
  26. void Push(Item item);
  27. int IsEmpty();
  28. };
  29. template<class Item>
  30. MyStack<Item>::MyStack()
  31. {
  32. head=NULL;
  33. top=0;
  34. }
  35. template<class Item>
  36. MyStack<Item>::~MyStack()
  37. {
  38. while(NULL != head)
  39. {
  40. StackNode<Item>* tmp=head->next;
  41. delete head;
  42. head=tmp;
  43. }
  44. }
  45. template<class Item>
  46. Item MyStack<Item>::Pop()
  47. {
  48. if(IsEmpty())
  49. {
  50. cout<<"stack is empty,cannot pop any more!"<<endl;
  51. return ((head->s)[top]);
  52. }
  53. if(top==-1)
  54. {
  55. StackNode<Item>* tmp=head->next;
  56. delete head;
  57. head=tmp;
  58. top=MAXNUM-1;
  59. }
  60. return ((head->s)[top--]);
  61. }
  62. template<class Item>
  63. void MyStack<Item>::Push(Item item)
  64. {
  65. if(head==NULL)
  66. {
  67. head=new StackNode<Item>;
  68. if(head==NULL)
  69. {
  70. cout<<"initial stack error----malloc error"<<endl;
  71. return ;
  72. }
  73. top=0;
  74. }
  75. top++;
  76. if(top==MAXNUM)
  77. {
  78. StackNode<Item>* NewNode=new StackNode<Item>;
  79. NewNode->next=head;
  80. head=NewNode;
  81. top=0;
  82. }
  83. (head->s)[top]=item;
  84. }
  85. template<class Item>
  86. int MyStack<Item>::IsEmpty()
  87. {
  88. return ((head==NULL)||((head->next==NULL)&&(top==0)));
  89. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注