![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
//栈的表现和实现
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define OVERFLOW -2
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define Stack_init_size 100
#define Stackincrement 10
struct Sqstack
{
char *base;
char *top;
int stacksize;
};
int InitStack(struct Sqstack *s)//初始化栈
{
s->base=(char *)malloc(Stack_init_size*sizeof(char));
if(!s->base)
exit(OVERFLOW);
s->top=s->base;
s->stacksize=Stack_init_size;
return OK;
}
int StackEmpty(struct Sqstack *s)//若栈为空,则返回TRUE,否则返回FALSE
{
if(s->top==s->base)
return TRUE;
else
return FALSE;
}
int GetTop(struct Sqstack *s,char *e)//若栈不空,则用e返回s的栈顶元素,并返回OK;否则返回ERROR
{
if(s->top==s->base)
return ERROR;
*e=*(s->top-1);
return OK;
}
int Push(struct Sqstack *s,char e)//插入元素e为新的栈顶元素
{
if(s->top-s->base>=s->stacksize)
{
s->base=(char *)realloc(s->base,(s->stacksize+Stackincrement)*sizeof(char));
if(!s->base)
exit(OVERFLOW);
s->top=s->base+s->stacksize;
s->stacksize+=Stackincrement;
}
*s->top++=e;
return OK;
}
int Pop(struct Sqstack *s,char *e)//若栈不空,则删除s的栈顶元素,并用e返回其值,并返回OK,否则返回ERROR
{
if(s->top==s->base)
return ERROR;
*e=*(--s->top);
return OK;
}
//对于输入的任意一个非负十进制整数,打印输出与其等值的八进制数
void conversion()
{
Sqstack s;
int N;
char e;
InitStack(&s);
scanf("%d",&N);
while(N)
{
Push(&s,N%8);
N=N/8;
}
while(!StackEmpty(&s))
{
Pop(&s,&e);
printf("%d",e);
}
}//conversion
int main()
{
printf("Input:\n");
conversion();
printf("\n");
return OK;
}
![](https://www.cnblogs.com/Emoticons/tusiji/202939796.gif)
![](https://www.cnblogs.com/Emoticons/tusiji/202939796.gif)
![](https://www.cnblogs.com/Emoticons/tusiji/202939796.gif)