#include<stdio.h>
#include<malloc.h>
#define STACK_INIT_SIZE 100//初始分配量
#define STACKINCREMENT 10//存储空间分配增量
#define ERROR 0
#define OK 1
#define OVERFLOW -2
typedef int SElemType;
typedef int Status;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
//得到当前栈的长度
int GetLen(SqStack &S){
if(!S.base) return 0;
return S.top-S.base;
}
//打印当前栈的元素
Status PrintStack(SqStack &S){
if(!S.base) return ERROR;
int len=GetLen(S);
SElemType *temp=S.top;//把当前的top赋值给一个临时变量,不能直接使用top
printf("长度:%d\n",len);
printf("栈元素:");
while(temp!=S.base ){
printf("%d,",*--temp);
}
printf("\n");
}
//初始化
Status InitStack(SqStack &S){
S.base=(SElemType *)malloc(sizeof(SElemType)*STACK_INIT_SIZE);
if(!S.base){
exit(OVERFLOW);
}
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}
//得到某个元素
SElemType GetTop(SqStack &S){
if(S.top==S.base)
return ERROR;
return *(S.top-1);
}
//对该栈进行添加元素
Status Push(SqStack &S,SElemType e){
if(S.top-S.base>=S.stacksize){
S.base=(SElemType*)realloc(S.base,sizeof(SElemType)*(S.stacksize+STACKINCREMENT));
if(!S.base) exit(OVERFLOW);
S.top=S.base+S.stacksize;//因为是栈满才进行增加空间,所以top是在栈底加上栈满时的位置
S.stacksize+=STACKINCREMENT;
}
*(S.top++)=e;
return OK;
}
//弹出该栈中的元素,并把栈的长度减1
SElemType Pop(SqStack &S){
if(!S.base) return ERROR;
if(S.top==S.base) return OVERFLOW;
return *--S.top;
}
//数制转换
void conversion(){
int n=1348;//十进制n
int d=8;//其他d进制数
int mod=0;
SqStack S;
InitStack(S);
while(n>0){
mod=n%d;
n=(n/d);
Push(S,mod);
}
PrintStack(S);
}
int main(){
SqStack S;
// InitStack(S);
// PrintStack(S);
// Push(S,4);
// PrintStack(S);
// Push(S,6);
// PrintStack(S);
// SElemType e=Pop(S);
// printf("%d\n",e);
// PrintStack(S);
conversion();
return 0;
}