#pragma onceconstint MaxSize =100;template<classT>classStack{public:Stack();~Stack(){}voidPush(T x);
T GetTop();
T ChuTop();boolEmpty();private:
T data[MaxSize];int top;};
Stack.cpp
#include"Stack.h"template<classT>
Stack<T>::Stack(){
top =-1;}template<classT>void Stack<T>::Push(T x){if(top == MaxSize -1)throw"上溢";
top++;
data[top]= x;}template<classT>
T Stack<T>::ChuTop(){if(top !=-1)return data[top];}template<classT>
T Stack <T>::GetTop(){
T x;if(top ==-1)throw"下溢";
x = data[top--];return x;}template<classT>bool Stack<T>::Empty(){if(top ==-1)return1;elsereturn0;}
main.cpp
#include"Stack.cpp"#include<iostream>usingnamespace std;int j =0;voidmain(){
Stack<int> a;//创建模板类的实例if(a.Empty()){int c, d, e;
cout <<"请输入一个十进制的数字:";
cin >> d;try{
cout <<"将十进制的数转化成二进制的数的入栈顺序为:";while(d !=0)//将十进制数依次对二取余,将余数入栈{
e = d %2;
c = d /2;
d = c;
j++;
a.Push(e);}
cout << endl;}catch(char* wrong){
cout << wrong;}
cout <<"将从键盘输入的数转换成二进制并执行入栈操作:"<< endl;
cout <<"转换后的二进制数执行出栈操作:"<< endl;
cout <<"二进制数为:"<< endl;for(int m =1; m <= j; m++){
cout << a.ChuTop();//执行出栈操作,即得到转换后的二进制数;}}else{
cout <<"栈不空"<< endl;}system("pause");}
链栈实现
LinkStack.h
#pragma oncetemplate<classT>struct Node
{
T data;
Node<T>*next;//此处<T>也可以省略};template<classT>classLinkStack{public:LinkStack();/* {
top = NULL;
}*/~LinkStack(){}voidPush(T x);
T Pop();
T GetTop();boolEmpty();private:
Node<T>*top;};
LinkStack.cpp
#include"LinkStack.h"template<classT>
LinkStack<T>::LinkStack(){
top =new Node<T>; top =0;}template<classT>void LinkStack<T>::Push(T x){
Node<T>*s;
s =new Node<T>;
s->data = x;
s->next = top;
top = s;}template<classT>
T LinkStack<T>::Pop(){
T x;
Node<T>*p;if(top ==0)throw"下溢";
x = top->data;
p = top;
top = top->next;delete p;return x;}template<classT>
T LinkStack<T>::GetTop(){if(!top ==0)return top->data;}template<classT>bool LinkStack<T>::Empty(){if(top ==0)return1;elsereturn0;}
LinkStackMain.cpp
#include"LinkStack.cpp"#include<iostream>usingnamespace std;int j =0;voidmain(){
LinkStack <int> a;if(a.Empty()){int c, d, e;
cout <<"请输入一个十进制的数字:";
cin >> d;try{
cout <<"将十进制的数转化成二进制的数的入栈顺序为:";while(d !=0)//将十进制数依次对二取余,将余数入栈{
e = d %2;
c = d /2;
d = c;
j++;
a.Push(e);}
cout << endl;}catch(char* wrong){
cout << wrong;}
cout <<"将从键盘输入的数转换成二进制并执行入栈操作:"<< endl;
cout <<"二进制数为:"<< endl;for(int m =1; m <= j; m++)//j为转换为二进制后的位数{
cout << a.Pop();//执行出栈操作,即得到转换后的二进制数;}}else{
cout <<"栈不空"<< endl;}system("pause");}