用栈将十进制数字转化为八进制数字

#include
#include

#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OVERFLOW -3
#define OK 1
#define ERROR 0

typedef int SElemType;
typedef int Status;
typedef struct
{
	SElemType *top;
	SElemType *base;
	int stacksize;
}SqStack;

Status InitStack(SqStack *S)	//初始化顺序栈
{
	S->base=(SElemType*)malloc(sizeof(SElemType)*STACK_INIT_SIZE);
	if(!(S->base))
		exit(OVERFLOW);
	S->stacksize=STACK_INIT_SIZE;
	S->top=S->base;
	return OK;
}

Status Push(SqStack *S,SElemType 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;
	S->top++;
	return OK;
}

Status Pop(SqStack *S,SElemType *e)	//出栈
{
	if(S->base==S->top)
		return ERROR;
	*e=*(--(S->top));
	return OK;
}

Status StackTraverse(SqStack S)
{
	int i;
	SElemType *p;
	p=S.base;
	for(i=1;i<=S.top-S.base;i++)
	{
		printf("第%d个元素为:%d\n",i,*p);
		p++;
	}
	return OK;
}

Status DestroyStack(SqStack *S)
{
	free(S->base);
	S->base=NULL;
	S->top=NULL;
	S->stacksize=0;
	return OK;
}

int main()
{
	SqStack S;
	int n,e,a;
	printf("该程序为利用栈将10进制转化为8进制的一个小程序!\n");
	printf("请输入一个数字:");
	scanf("%d",&n);
	a=n;
	InitStack(&S);
	while(n)
	{
		Push(&S,n%8);
		n=n/8;
	}
	printf("%d在八进制中为:",a);
	while(S.base!=S.top)
	{
		Pop(&S,&e);
		printf("%d",e);
	}
	printf("\n");
	return 0;
}

你可能感兴趣的:(c语言)