//函数声明:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_MEMORY 100
#define STACK_GROW_MEMORY 10
typedef int ElemType;
typedef struct stack
{
ElemType *esp;
ElemType *ebp;
int size; //记录当前栈内空间最多能存几个元素
}stack;
//函数实现:
void creatstack(stack *S)
{
S->ebp = (ElemType *)malloc(sizeof(ElemType)* STACK_INIT_MEMORY);
if (S->ebp == NULL) //判断动态内存是否开辟成功
exit(1);
S->size = STACK_INIT_MEMORY;
S->esp = S->ebp;
}
int push(stack *S, ElemType x)
{
if (S->esp - S->ebp >= S->size) //判断当前栈是否已满
{ //栈满追加空间
S->ebp = (ElemType *)realloc(S->ebp, sizeof(ElemType)*(S->size + STACK_GROW_MEMORY));
if (S->ebp == NULL)
exit(1);
S->esp = S->ebp + S->size; //让栈顶指针向后偏移指向要入栈的位置
S->size += STACK_GROW_MEMORY;
}
*S->esp++ = x;
return 1;
}
int pop(stack *S, ElemType *x)
{
if (S->esp == S->ebp)
return 0;
else
{
*x = *--S->esp;
return 1;
}
}
int getesp(stack *S, ElemType *x)
{
if (S->esp == S->ebp)
return 0;
else
{
*x = *(S->esp - 1);
return 1;
}
}
int stacklength(stack *S)
{
return S->esp - S->ebp;
}
void destorystack(stack *S)
{
if (S->ebp != NULL) //销毁栈
free(S->ebp);
}
//函数测试:
#include"stack.h"
int main()
{
printf("************************************\n");
printf("*0.exit 1.creatstack *\n");
printf("*2.push 3.pop *\n");
printf("*4.getesp 5.stacklength *\n\n\n");
stack ret;
ret.ebp = NULL;
ElemType x;
int n = 0;
while (1)
{
printf("请选择功能:");
scanf("%d", &n);
switch (n)
{
case 0:
destorystack(&ret);
exit(1);
break;
case 1:
if (ret.ebp != NULL)
{
destorystack(&ret); //如果当前已经创建了一个栈,则先销毁在创建
}
creatstack(&ret);
printf("创建成功\n");
break;
case 2:
printf("请输入入栈元素:");
scanf("%d", &x);
push(&ret, x);
printf("入栈成功\n");
break;
case 3:
if (pop(&ret, &x) == 0)
printf("栈是空栈!\n");
else
printf("弹出成功,弹出元素:%d\n", x);
break;
case 4:
if (getesp(&ret,&x) == 0)
printf("栈是空栈!\n");
else
printf("栈顶元素:%d\n",x);
break;
case 5:
printf("栈的长度:%d\n", stacklength(&ret));
break;
default:
printf("选择无效\n");
break;
}
}
system("pause");
return 0;
}
转载于:https://blog.51cto.com/11142019/1767004