【學習點點滴滴】 棧的應用很多,這裏定義的棧實現數之間的轉換,用兩個出棧函數分別實現二進制和十六進制的轉換。
#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);
}