#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define INITSIZE 10
#define INCREASESIZE 10
#define syserr(msg) {perror(msg);exit(-1);}
typedef int ElemType;
typedef struct Stack{
int capacity,top;
ElemType *base;
}*SequenceStack;
void StackInit(SequenceStack* S)
{
*S = (SequenceStack)malloc(sizeof(struct Stack));
if(!*S)syserr("malloc");
(*S)->base = (ElemType *)malloc(sizeof(ElemType)*INITSIZE);
if(!(*S)->base)syserr("malloc");
(*S)->top = -1;
(*S)->capacity = INITSIZE;
}
void StackDestroy(SequenceStack* S)
{
free((*S)->base);
free(*S);
*S = NULL;
}
int isEmpty(SequenceStack S)
{
return (S->top == -1);
}
void Push(SequenceStack S,ElemType e)
{
if(S->top+1 == S->capacity)
{
S->base = (ElemType*)realloc(S->base,sizeof(ElemType)*(S->capacity+INCREASESIZE));
S->capacity += INCREASESIZE;
if(!S->base)printf("realloc fail/n");
//printf("Stack realloc/n");
}
S->top++;
S->base[S->top]=e;
//printf("push %d:%d/n",S->top,S->capacity);
}
void Pop(SequenceStack S,ElemType *e)
{
if(isEmpty(S))syserr("empty");
*e = S->base[S->top];
S->top--;
}
void GetTop(SequenceStack S,ElemType *e)
{
if(isEmpty(S)) syserr("empty");
*e = S->base[S->top];
}
void TestForStack()
{
SequenceStack S1,S2;
ElemType e;int d,b;
StackInit(&S1);
StackInit(&S2);
scanf("%d,%d",&d,&b);
while(d)
{
Push(S1,d%b);
d/=b;
}
while(!isEmpty(S1))
{
Pop(S1,&e);
printf("%d ",e);
}
StackDestroy(&S1);
StackDestroy(&S2);
}
int main(int argc,char *argv[])
{
TestForStack();
}
栈的实现和应用(进制转化)
最新推荐文章于 2024-10-29 21:09:12 发布