一、创建三个文件
二、代码实现
1.Stack.c部分
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>
#include "Stack.h"
enum Option
{
退出栈,
压栈,
出栈,
查看栈数据,
访问栈顶
};
void menu()
{
printf("*************************************************\n");
printf("****** 1.压栈 2.出栈 ******\n");
printf("****** 3.查看栈数据 4.访问栈顶 ******\n");
printf("****** 0.退出栈 ******\n");
printf("*************************************************\n");
}
int main()
{
int input = 0;
ST pStack;
StackInit(&pStack);
do
{
menu();
printf("请选择要进行的操作:");
scanf("%d", &input);
switch (input)
{
case(压栈):
StackPush(&pStack);
break;
case(出栈):
StackPop(&pStack);
break;
case(查看栈数据):
StackLook(&pStack);
break;
case(访问栈顶):
StackTopLook(&pStack);
break;
case(退出栈):
StackDestroy(&pStack);
break;
default:
printf("输入有误,请重新输入\n");
break;
}
} while (input);
return 0;
}
2.Stack.h部分
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>
//1.定义结构
typedef struct Stack
{
int* a;
int top;
int capacity;
}ST;
//2.数组栈初始化函数声明
void StackInit(ST* pStack);
//3.压栈函数声明
void StackPush(ST* pStack);
//4.出栈函数声明
void StackPop(ST* pStack);
//5.查看栈函数声明
void StackLook(ST* pStack);
//6.访问栈顶函数声明
void StackTopLook(ST* pStack);
//7.栈空间回收函数声明
void StackDestroy(ST* pStack);
3.StackFunc.c部分
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>
#include "Stack.h"
//2.数组栈初始化函数实现
void StackInit(ST* pStack)
{
assert(pStack);
pStack->a = NULL;
pStack->top = 0;
pStack->capacity = 0;
}
//3.压栈函数实现
void StackPush(ST* pStack)
{
assert(pStack);
if (pStack->capacity == pStack->top)
{
int newcapacity = pStack->capacity == 0 ? 4 : (pStack->capacity + 4);
int* newpStack = (int*)realloc(pStack->a, newcapacity * sizeof(int));
if (newpStack == NULL)
{
printf("StackPush::()%s\n", strerror(errno));
exit(-1);
}
pStack->a = newpStack;
pStack->capacity = newcapacity;
}
printf("请输入要压栈的数值:");
int x = 0;
scanf("%d", &x);
pStack->a[pStack->top] = x;
pStack->top++;
}
//4.出栈函数实现
void StackPop(ST* pStack)
{
assert(pStack);
if (pStack->top > 0)
{
pStack->top--;
}
else
{
printf("已无数据,无法出栈\n");
}
}
//5.查看栈函数实现
void StackLook(ST* pStack)
{
assert(pStack);
int i = 0;
if (pStack->top <= 0)
{
printf("栈元素为空\n");
}
else
{
for (i = pStack->top - 1; i >= 0; i--)
{
printf("%d ", pStack->a[i]);
}
}
printf("\n");
}
//6.访问栈顶函数实现
void StackTopLook(ST* pStack)
{
assert(pStack);
if (pStack->top > 0)
{
printf("栈顶元素为%d\n", pStack->a[pStack->top-1]);
}
else
{
printf("栈内无元素\n");
}
}
//7.栈空间回收函数实现
void StackDestroy(ST* pStack)
{
assert(pStack);
free(pStack->a);
pStack->a = NULL;
pStack->capacity = 0;
pStack->top = 0;
}