【学习点点滴滴】 栈的应用很多,这里定义的栈实现数之间的转换,用两个出栈函数分别实现二进制和十六进制的转换。
#include <iostream.h>
#include <stdlib.h>
template <class type>
class seqstack
{
private:
int top;//栈顶指示
type * stacka;//数组名
int maxsize;//栈的最大容量
public:
seqstack(int size);
~seqstack( )
{
delete [ ] stacka;
}
void push(const type &item);//入栈
void pop(void);//出栈
type gettop( );//获取栈顶元素
int empty(void) const //栈空否
{
return top==-1;
}
int full( ) const//栈满否
{
return top==maxsize-1;
}
void clear(void)//清空栈
{
top=-1;
}
};
template <class type>
seqstack <type>::seqstack(int size):
top(-1),maxsize(size)
{
stacka=new type[maxsize];//创建存储栈的数组
if(stacka==NULL)//分配失败
{
cerr<<"Allocation failed!"<<endl;
exit(1);
}
}
template <class type>
void seqstack<type>::push(const type &item)
{
if(full( ))//入栈,如果栈满
{
cout<<"The stack is full,item can't be pushed"<<endl;
exit(1);
}//栈未满,入栈,
else
{
stacka [++top]=item;
}
}
template <class type>
void seqstack<type> ::pop( )
{
if(empty( ))//出栈,若为空栈
{
cout<<"The stack is empty,no item can be poped"<<endl;
exit(1);
}//栈非空,出栈
else
{
while(top!=-1)
{
cout<<stacka [top];
top--;
}
cout<<endl;
}
}
template <class type>
type seqstack<type>::gettop( )
{
if(empty( ))
{
cout<<"The stack is empty,no item can be poped"<<endl;
exit(1);
}
//返回栈顶元素
else
{
return stacka [top];
}
}
//const int size=20;
#include "seqstack.H"
void conversion(int N)//函数,将十进制数N转换为二进制数
{
seqstack<int> stack(30);//假定栈的最大容量为30
//用来存放出栈的元素
while(N!=0)
{
int b=N%2;
stack.push(b);
N=N/2;
}
stack.pop();
}
void conver(int N)//函数,
{
seqstack<int> tack(30);//假定栈的最大容量为30
while(N!=0)
{
int b=N%16;
if(b<=9)
tack.push(b);
else
tack.push(b+55);
N=N/16;
}
tack.pop();
}
void main( )
{
conversion(95);//调用函数conversion,将95转换为二进制数
conver(24);
}