顺序堆栈实现数制转换以十进制数转化为八进制数为例

顺序堆栈实现数制转换以十进制数转化为八进制数为例_第1张图片

//数据结构 第三章栈和队列
#include
#include
#define OVERFLOW -2
#define FALSE 0
#define TRUE 1
#define OK 1
#define ERROR 0

typedef int Status;
//栈的顺序存储表示

#define STACK_INIT_SIZE 100 //存储空间的初始分配量
#define STACKINCREAMENT 10  //存储空间分配增量

//栈的元素类型
typedef char SElemType;

typedef struct
{
	SElemType *base;  //构造之前和销毁之后base的值为NULL
	SElemType *top;   //栈顶指针
	int stacksize;    //当前已分配的存储空间
}SqStack;
Status InitStack(SqStack *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 Push(SqStack *S,SElemType e)
{
	if(S->top-S->base>=S->stacksize)//栈满,追加存储空间
	{
		S->base=(SElemType *)realloc(S->base,(S->stacksize+STACKINCREAMENT)*sizeof(SElemType));
		if(!S->base) exit(OVERFLOW);
		S->top=S->base+S->stacksize;
		S->stacksize+=STACKINCREAMENT;
	}
	//入栈操作,完成操作后,top指针加1
	*S->top++=e;
	return OK;
}
Status Pop(SqStack *S,SElemType *e)
{
	if(S->base==S->top) return ERROR;
	*e=*--S->top;
	return OK;
}
Status StackEmpty(SqStack S)
{
	if(S.base==S.top)
	{
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

十进制数转化为八进制数

void conversion(SqStack *S)
{
	//对于输入的任意一个非负十进制整数,打印输出其八进制数
	SElemType quotient;
	int N;
	InitStack(S);
	printf("This is a program that concerts decimal numbers to octal numbers,\nplease enter the decimal number:");
	scanf("%d",&N);
	while(N)
	{
		Push(S,N%8);
		N=N/8;
	}
	while(!StackEmpty(*S))
	{
		Pop(S,&quotient);
		printf("%d",quotient);
	}
	printf("\n");
}

void main()
{
	SqStack S;
	conversion(&S);
}

你可能感兴趣的:(数据结构)