首页 > 其他 > 详细

链式栈简单模板代码

时间:2015-10-22 21:17:54      阅读:297      评论:0      收藏:0      [点我收藏+]
  1 #include<iostream>
  2 #include<stdlib.h>
  3 using namespace std;
  4 
  5 template <class T>
  6 class LinkStack;
  7 template <class T>
  8 class StackNode
  9 {
 10 public:
 11     friend class LinkStack<T>;
 12 private:
 13     T data;
 14     StackNode<T> *next;
 15 };
 16 template<class T>
 17 class LinkStack
 18 {
 19 public:
 20     LinkStack() { top = NULL; }
 21     ~LinkStack();
 22     bool StackEmpty() 
 23     { return top ==NULL; }
 24     void Push(T x);
 25     void Pop(T &x);
 26     T GetTop();
 27 
 28 private:
 29     StackNode<T>*top;
 30 };
 31 template<class T>                     //入栈
 32 void LinkStack<T>::Push(T x)
 33 {
 34     StackNode<T> *p;
 35     p = new StackNode<T>;
 36     p->data = x;
 37     p->next = top;
 38     top = p;
 39 }
 40 template <class T>                 //返回栈顶元素
 41 T LinkStack<T>::GetTop()
 42 {
 43     if (StackEmpty())
 44     {
 45         cout << "为空" << endl;
 46         return -1;
 47     }
 48     else return top->data;
 49 }
 50 template <class T>                   //出栈
 51 void LinkStack<T>::Pop(T &x)
 52 {
 53     StackNode<T> *p = top;
 54     if (StackEmpty())
 55     {
 56         cout << "为空" << endl;
 57     }
 58     else
 59     {
 60         x = p->data;
 61         top = p->next;
 62         delete p;
 63     }
 64 }
 65 template <class T>           
 66 LinkStack<T>::~LinkStack()        //析构函数
 67 {
 68     StackNode <T> *s;
 69     while (top)
 70     {
 71         s = top->next;
 72         delete top;
 73         top = s;
 74     }
 75 }
 76 
 77 void conversion(int N, int d)         //进制转换
 78 {
 79     LinkStack<int>S;
 80     int i;
 81     while (N)
 82     {
 83         S.Push(N%d);
 84         N = N / d;
 85 
 86     }
 87     while (!S.StackEmpty())
 88     {
 89         S.Pop(i);
 90         cout << i;
 91 
 92     }
 93     cout << endl;
 94 }
 95 void main()
 96 {
 97     int N(64), d(2);
 98     cout<<"十进制64转化为二进制:";
 99     conversion(N, d);
100     system("PAUSE");
101     return;
102 }

 

链式栈简单模板代码

原文:http://www.cnblogs.com/jamylu/p/4902564.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!