C语言堆栈的实现

使用C语言实现堆栈的初始化,入栈,出栈操作

#include<stdio.h>
#include<stdlib.h>
typedef int elemtype;

#define STACK_INIT_SIZE 20
#define STACKINCREMENT  10

typedef struct
{
	elemtype   * base;
	elemtype  *  top;
	int  stacksize;
}SqStack;

int Inistack(SqStack &s)
{
	s.base = (elemtype *)malloc(STACK_INIT_SIZE * sizeof(elemtype));
	if (!s.base)
		exit(0);
	s.top = s.base;
	s.stacksize = STACK_INIT_SIZE;
	return 1;
}

int push(SqStack &s, elemtype e)
{
	if (s.top - s.base >= s.stacksize)
	{
		s.base = (elemtype *)realloc(s.base, (s.stacksize + STACKINCREMENT) * sizeof(elemtype));
		if (!s.base)
			exit(0);
		s.top = s.base + s.stacksize;
		s.stacksize += STACKINCREMENT;
	}
	*(s.top++) = e;
	return 1;
}

int pop(SqStack &s)
{
	elemtype e;
	if (s.top == s.base)
		exit(0);
	e = *(--s.top);
	return e;
}

int main()
{
	SqStack s;
	Inistack(s);
	int num;
	int a[6] = { 12,43,34,16,19,20 };	//12,43,34,16,19,20
	printf("将入栈12,43,34,16,19,20这6个元素\n");
	for (int i = 0; i < 6; i++)
	{
		push(s, a[i]);
	}
	printf("请输入要出栈的个数:");
	scanf("%d", &num);
	printf("出栈的元素为:\n");
	for (int i = 0; i < num; i++)
	{
		printf("%d ", pop(s));
	}
	printf("\n");
	system("pause");
	int str[100];
	scanf("%s", &str);

}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值