Stack.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
//定义栈内数据类型
typedef int DateType;
//定义栈空间大小
#define MaxSize 20
//定义栈的结构体
typedef struct Stack
{
DateType arr[MaxSize];
int top;
}Stack;
//初始化栈
void InitStack(Stack *p);
//销毁栈
void Destroy(Stack *p);
//压栈
void PushStack(Stack *p, DateType data);
//出栈
void PopStack(Stack *p);
//查看栈顶的元素
DateType TopStack(Stack *p);
//判断当前栈是否为空
int IsEmpty(Stack *p);
//当前栈空间大小
int StackSize(Stack *p);
//打印栈
void print(Stack *p);
//测试用例
void test();
Stack.c
#include"Stack.h"
//初始化栈
void InitStack(Stack *p)
{
assert(p);
p->top = 0;
}
//销毁栈
void Destroy(Stack *p)
{
assert(p);
p->top = 0;
}
//压栈
void PushStack(Stack *p,DateType data)
{
assert(p);
assert(p->top<MaxSize);//判断当前栈空间是否已满
p->arr[p->top++] = data;//注意是top++而不是top
}
//出栈
void PopStack(Stack *p)
{
assert(p);
assert(p->top>0);//判断当前栈是否为空
p->top--;//删除栈顶的元素
}
//查看栈顶的元素
DateType TopStack(Stack *p)
{
assert(p);
assert(p->top>0);//判断当前栈是否为空
return p->arr[p->top-1];//返回栈顶的元素
}
//判断当前栈是否为空
int IsEmpty(Stack *p)
{
return p->top == 0 ? 1 : 0; //为空则返回1,不为空返回0
}
//当前栈空间大小
int StackSize(Stack *p)
{
return p->top;
}
void Print(Stack *p)
{
int i = 0;
for (i = 0; i < p->top; i++)
{
printf("%d", p->arr[i]);
}
printf("\n");
}
void test()
{
Stack *pS;
InitStack(&pS);
Print(&pS);
PushStack(&pS, 1);
PushStack(&pS, 3);
PushStack(&pS, 2);
PushStack(&pS, 9);
PushStack(&pS, 6);
printf("%d\n", TopStack(&pS));//返回栈顶的元素
Print(&pS);
PopStack(&pS);
PopStack(&pS);
printf("%d\n", StackSize(&pS));
PopStack(&pS);
PopStack(&pS);
printf("%d\n", IsEmpty(&pS));//不为空返回0
Print(&pS);
Destroy(&pS);
Print(&pS);
printf("%d\n",IsEmpty(&pS));//为空返回1
}
main.c
#include"Stack.h"
int main()
{
test();
system("pause");
return 0;
}