一个动态数组实现的简单栈

这篇博客介绍了一个基于动态数组实现的简单栈。通过`Init_Stack()`初始化栈,`push()`进行压栈操作,`pop()`进行弹栈操作。栈的初始大小为100,当接近满时,会按10个元素的增量进行动态扩容。在`main()`函数中展示了压栈和弹栈的过程。

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

/******************************************************

一个动态数组实现的简单栈

******************************************************/
#include<stdio.h>
#include<stdlib.h>
#define STACK_SIZE 100      /*  栈初始向量大小  */
#define STACKINCREMENT 10   /*  存储空间分配增量  */
#define OK 1
#define ERROR 0
typedef int ElemType;
typedef struct sqstack
{
    ElemType *bottom;      	/*	栈不存在时值为NULL	*/
	ElemType *top;       	/*	栈顶指针  */
	ElemType stacksize;  	/*	当前已分配空间,以元素为单位  */
}SqStack;
SqStack Init_Stack()
{
	SqStack S;
	S.bottom=(ElemType *)malloc(STACK_SIZE*(sizeof(ElemType)));
	if(!S.bottom)
	{
	    exit(ERROR);
	}
	S.top = S.bottom;           	/*	栈空时栈顶和栈底指针相同  */
	S.stacksize = STACK_SIZE;
	return S;
}
int push(SqStack *S,ElemType e)
{
    if((*S).top-(*S).bottom >= (*S).stacksize-1)	/*	栈满,追加存储空间	*/
    {
        (*S).bottom=(ElemType *)realloc((*S).bottom,((*S).stacksize+STACKINCREMENT)*sizeof(ElemType));
        if(!(*S).bottom)
        {
            return ERROR;
        }
		(*S).top=(*S).bottom+(*S).stacksize;
		(*S).stacksize+=STACKINCREMENT;
    }
	*(*S).top=e;
	(*S).top++;
	return OK;
}
int pop(SqStack *S,ElemType *e)                /*弹出栈顶元素*/
{
    if((*S).top == (*S).bottom)
    {
		printf("1\n");
        return ERROR;               /*	栈空,返回失败标志	*/
    }
	(*S).top--;
	*e=*(*S).top;
	return OK;
}
int main()
{
    int tmp=0,i=0;
	SqStack S;
	S=Init_Stack();
	for(i=0;i<10;i++)
	{
		push(&S,i);
	}
	for(i=0;i<10;i++)
	{
		pop(&S,&tmp);
		printf("%d\n",tmp);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值