顺序栈(进制转换),包括一系列的操作

本文介绍了一个使用顺序栈实现从十进制数转换到八进制数的程序设计过程。通过定义栈的基本操作如初始化、压栈、弹栈等,实现了将输入的十进制数逐步转换为八进制形式的功能,并完整展示了转换过程。

#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef enum{OK,ERROR,TURE,FLASE}Status;
typedef struct
{
 int *base;
 int *top;
 //栈容量
 int stacksize;
}SqStack;
//顺序栈的初始化
Status InitStack(SqStack& S)
{
 S.base = new int[MAXSIZE];

 if(!S.base)exit(1);
 S.top = S.base;
 S.stacksize = MAXSIZE;

 return OK;
}
//push
Status Push(SqStack& S,int e)
{
 if(S.top - S.base == S.stacksize)
  return ERROR;
 *S.top++ = e;
 return OK;
}
//POP
Status Pop(SqStack& S,int& e)
{
 if(S.base == S.top)return ERROR;

 e = *--S.top;
 return OK;
}
//遍历
Status StackTraverse(SqStack& S)
{
 if(S.base == S.top)exit(1);
 int *p = S.base;
 while(p != S.top)
 {
  cout<<*p++<<" ";

 }
 return OK;
}

//Gettop
int GetTop(SqStack& S)
{
 if(S.base == S.top)exit(1);
 return *(S.top-1);
}

//判断站是否为空
Status StackEmpty(SqStack& S)
{
 if(S.top == S.base)return FLASE;
 else
 {
  return TURE;
 }
}
//取栈长度
Status StackLength(SqStack& S,int& length)
{
 if(S.base == S.top)exit(1);
 length = S.top - S.base;
 return OK;
}
//清空栈
Status ClearStack(SqStack& S)
{
 if(S.base == S.top)exit(1);
 int * p = S.base;
 while(p != S.top)
 {
  *p++ = 0;
 }
 return OK;
}
//销毁
Status DestroyStack(SqStack& S)
{
 if(S.top == S.base)exit(1);
 delete [] S.base;
 S.base = NULL;
 S.top = NULL;
 return OK;
}
int main()
{
 Status Sta;
 SqStack S;
 Sta = InitStack(S);
 if(Sta == OK)
 {
  cout<<"栈的初始化成功!"<<endl;
 }
 int N,length;
 cout<<"十进制: ";
 cin>>N;
 while(N)
 {
  Push(S,N%8);
  N = N / 8;
 }
 StackLength(S,length);
 cout<<"栈的长度: "<<length<<endl;

 cout<<"栈的遍历: ";
 Sta = StackTraverse(S);
 if(Sta == OK)cout<<endl<<"遍历成功!"<<endl;


 int e = 0;
 cout<<"八进制: ";
 while(StackEmpty(S) == TURE)
 {
  Pop(S,e);
  cout<<e;
 }
 cout<<endl;
 Sta = DestroyStack(S);
 if(Sta == OK)cout<<"成功销毁栈!"<<endl;
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值