数据结构---栈

实验内容

(1)顺序栈应用:编制一C++程序prog_stack,实现如下功能:

1)   定义一顺序栈(动态栈)名为 TranSqstack, 实现如下基本操作:

 InitStack:构造一空栈,初始大小(STACK_INIT_SIZE)设为50, 基本数据类型(ElemType)设为 int。

 DestroyStack: 

 IsEmpty: 

 GetTop:

 Push:

 Pop:

2)程序使用 TranSqstack 实现10进制数转换为16进制的功能,注意十六进制的数字字符为:0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F (其中A,B,C, D,E,F分别代表十进制的10,11,12,13,14,15, 例如十进制26用十六进制表示为0x1A)

3)程序从键盘读入十进制数, 然后显示该十进制数转换所得16进制数(注意,十六进制数前要加前缀0x)。

#include<iostream>
#include<cstdlib>
using namespace std;
#define  STACK_INIT_SIZE  50    /*  栈初始向量大小  */
#define STACKINCREMENT 10   /*  存储空间分配增量  */
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef  int  ElemType ;
typedef struct sqstack
{   ElemType  *bottom;     /*  栈不存在时值为NULL  */
    ElemType  *top;      /*  栈顶指针  */
    int   stacksize ;      
}SqStack ;
int InitStack(SqStack &S)    /* 初始化  */
{
S.bottom = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if(!S.bottom)exit(OVERFLOW);
S.top = S.bottom;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
bool IsEmpty(SqStack &S)    /*  判断是否为空栈  */
{
if(S.top == S.bottom)
return true;
else
return false;
}
int GetTop(SqStack S,ElemType &e)    /*  若栈不空,则用e返回S的栈顶元素  */
{
if(S.top == S.bottom)return OK;
e = *(S.top - 1);
return OK;
}
int Push(SqStack &S,ElemType e)     /*  进栈  */
{
if(S.top - S.bottom >= S.stacksize)
{
S.bottom = (ElemType *)realloc(S.bottom,(S.stacksize + STACKINCREMENT) * sizeof(ElemType));
if(!S.bottom)exit(OVERFLOW);
S.top = S.bottom + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top ++ = e;
return OK;
}
int Pop(SqStack &S,ElemType e)     /*  弹栈  */
{
if(S.top == S.bottom)return ERROR;
e = * --S.top;
return e;
}
int DestroyStack(SqStack &S)     /* 销毁栈S,S不再存在 */
 { 
   free(S.bottom);
   S.bottom = NULL;
   S.top = NULL;
   S.stacksize = 0;
   return OK;
 }
 int conversion(SqStack & S,int n,int base)     /* 进制转换函数 */
 {
  static char digit[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
  while(n > 0)
  {
  Push(S,digit[n % base]);
  n /= base;
}
}
int main()
{
SqStack S;
int n, a ;
scanf("%d", &n);
conversion(S, n, 16);
if(!IsEmpty(S))printf("%s","Ox");
while(!IsEmpty(S))printf("%c", Pop(S,* S.top ));
return 0; 
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值