您的位置:首页 > 理论基础 > 数据结构算法

用栈实现十进制转八进制在Win-TC下运行(数据结构)

2013-04-10 16:00 141 查看
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<conio.h>

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

typedef int SElemType;

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

int 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;
}

int 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;
/*printf("%d",*S->top);*/  /*检查出栈的结果*/
S->top++;
return OK;
}

int StackEmpty(SqStack *S)            /*判断栈是否为空*/
{
if(S->base==S->top)
return OK;
else
return ERROR;
}

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

void conversion()                      /*十进制转八进制*/
{
SqStack S;
int N;
int e;
InitStack(&S);
printf("Input the N:");
scanf("%d",&N);
while(N)
{
e= N%8;
printf("%d",e);
Push(&S,e);
N=N/8;
}
while(!StackEmpty(&S))
{
Pop(&S,&e);
printf("%d",e);
}
}

void main()
{
conversion();
getch();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: