栈的简单的经典的应用

【学习点点滴滴】 栈的应用很多,这里定义的栈实现数之间的转换,用两个出栈函数分别实现二进制和十六进制的转换。

#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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值