一、实验目的
掌握栈的逻辑结构特点。
掌握栈的各种基本操作。
熟练应用栈来解决实际的问题。
二、实验内容
数制转换。
利用栈实现数制转换,例如,将一个正整数(十进制)转换为与其等值的八进制整数。
三、源程序
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int Status;
typedef int SElemType;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status InitStack(SqStack &S){//构造一个空栈S
S.base=(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!S.base) exit(OVERFLOW);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}
Status GetTop(SqStack S,SElemType &e){//若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR
if(S.top==S.base) return ERROR;
e=*(S.top-1);
return OK;
}
Status Push(SqStack &S,SElemType e){//插入元素e为新的栈顶元素
if(S.top-S.base >= S.stacksize){//栈满,追加存储空间
S.base=(SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!S.base) exit(OVERFLOW);//存储分配失败
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;
return OK;
}
Status Pop(SqStack &S,SElemType &e){//若栈不空,则删除S的栈顶元素,用e返回元素,用e返回其值,并返回OK;否则返回ERROR
if(S.top==S.base) return ERROR;
e=* --S.top;
return OK;
}
void tentoeight(SqStack &S,int e){
while(e){
Push(S,e%8);
e=e/8;
}
}
void main(){
SqStack S;
int e,a;
scanf("%d",&e);
InitStack(S);
tentoeight(S,e);
while(Pop(S,a))
printf("%d",a);
};