【数据结构】·【链式栈】

前端之家收集整理的这篇文章主要介绍了【数据结构】·【链式栈】前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. #include<iostream>
  2. #include<assert.h>
  3. using namespace std;
  4.  
  5. template<class T>
  6. struct LinkNode{
  7. T data;
  8. LinkNode<T> * link;
  9. LinkNode(T& item,LinkNode<T> *ptr=NULL){
  10. data=item;
  11. link=ptr;
  12. }
  13. };
  14.  
  15. template<class T>
  16. class LinkedStack{
  17. public:
  18. LinkNode<T> *top;
  19.  
  20. LinkedStack():top(NULL){}
  21. ~LinkedStack(){
  22. makeEmpty();
  23. }
  24. void Push(T& x);
  25. bool Pop(T& x);
  26. bool getTop(T& x);
  27. bool IsEmpty();
  28. int getSize();
  29. void makeEmpty();
  30. //friend ostream& operator<<(ostream& os,LinkedStack<T>& s);
  31. };
  32.  
  33. template<class T>
  34. bool LinkedStack<T>::IsEmpty(){
  35. return (top==NULL)?true:false;
  36. }
  37.  
  38. template<class T>
  39. void LinkedStack<T>::makeEmpty(){
  40. LinkNode<T> *p;
  41. while(top!=NULL){
  42. p=top;
  43. top=top->link;
  44. delete p;
  45. }
  46. }
  47.  
  48. template<class T>
  49. void LinkedStack<T>::Push(T& x){
  50. top=new LinkNode<T>(x,top);
  51. assert(top!=NULL);
  52. }
  53.  
  54. template<class T>
  55. bool LinkedStack<T>::Pop(T& x){
  56. if(IsEmpty()==true)
  57. return false;
  58. LinkNode<T> *p=top;
  59. top=top->link;
  60. x=p->data;
  61. delete p;
  62. return true;
  63. }
  64.  
  65. template<class T>
  66. bool LinkedStack<T>::getTop(T& x){
  67. if(IsEmpty()==true)
  68. return false;
  69. x=top->data;
  70. return true;
  71. }
  72.  
  73. template<class T>
  74. int LinkedStack<T>::getSize(){
  75. LinkNode<T> *p=top;
  76. int k=0;
  77. while(top!=NULL){
  78. top=top->link;
  79. k++;
  80. }
  81. return k-1;
  82. }
  83.  
  84. /*
  85. template<class T>
  86. ostream& operator<<(ostream& os,LinkedStack<T>& s){
  87. os<<"栈中元素个数="<<s.getSize()<<endl;
  88. LinkNode<T> *p=s.top;
  89. int i=0;
  90. while(p!=NULL){
  91. os<<++i<<":"<<p->data<<endl;
  92. p=p->link;
  93. }
  94. }
  95. */
  96. void main(){
  97. LinkedStack<char> link;
  98.  
  99. int num;
  100. cout<<"输入数据个数:";
  101. cin>>num;
  102. char start=97;
  103. for(int i=0;i<num;i++){
  104. link.Push(start);
  105. start++;
  106. }
  107. for(int i=0;i<num;i++){
  108. link.Pop(start);
  109. cout<<start<<endl;
  110. }
  111. }

运行截图:

友元重载<<不懂为什么不行,知道的说下,谢谢。

猜你在找的数据结构相关文章