栈的实现和应用(进制转化)

本文介绍了一个使用C语言实现的动态数组栈,并通过该栈完成十进制数到任意进制数的转换过程。文章详细展示了栈的基本操作,如初始化、销毁、压栈、弹栈等,并提供了完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值