使用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);
}