实验内容
(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;
}