main.c
文件
#include"Stack.h"
int main()
{
StackTest();
system("pause");
return 0;
}
Stack.h
文件
#pragma once;
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#include<assert.h>
//栈 --后进先出
typedef int STDataType;
typedef struct Stack
{
STDataType *_a;//指针
int _top;//栈顶的下一个元素
int _capacity;//容量
}Stack;
void StackInit(Stack *ps, int n);
void StackDestory(Stack *ps);
void StackPush(Stack *ps, STDataType x);
void StackPop(Stack *ps);
STDataType StackTop(Stack *ps);
int StackSize(Stack *ps);
//空返回0,非空返回1
int StackEmpty(Stack *ps);
void StackTest();
Stack.c
文件
#include"Stack.h"
void StackInit(Stack *ps, int n)
{
assert(ps);
ps->_a = (STDataType *)malloc(sizeof(STDataType)*n);
//开辟空间是否成功
assert(ps->_a);
ps->_capacity = n;
ps->_top = 0;
}
void StackDestory(Stack *ps)
{
assert(ps);
if (ps->_top)
{
free(ps->_a);
ps->_a = NULL;
ps->_top = 0;
ps->_capacity = 0;
}
}
void StackPush(Stack *ps, STDataType x)
{
assert(ps);
//判断容量是否满
if (ps->_top == ps->_capacity)
{
ps->_a = realloc(ps->_a, sizeof(STDataType)*ps->_capacity * 2);
ps->_capacity *= 2;
}
ps->_a[ps->_top] = x;
ps->_top++;
}
void StackPop(Stack *ps)
{
assert(ps);
//判断还有没有数据可删
if (ps->_top > 0)
{
ps->_top--;
}
}
STDataType StackTop(Stack *ps)
{
assert(ps);
return ps->_a[ps->_top - 1];
}
int StackSize(Stack *ps)
{
assert(ps);
return ps->_top;
}
int StackEmpty(Stack *ps)
{
assert(ps);
return ps->_top == 0 ? 0 : 1;
}
void StackTest()
{
Stack ps;
StackInit(&ps,3);
StackPush(&ps, 1);
StackPush(&ps, 2);
StackPush(&ps, 3);
StackPush(&ps, 4);
StackPush(&ps, 5);
printf("Empty:%d\n", StackEmpty(&ps));
printf("Size:%d\n", StackSize(&ps));
/*Stack *cur = ps;
while (cur->_top)*/
while (ps._top)
{
printf("top=%d\n", StackTop(&ps));
StackPop(&ps);
}
printf("Empty:%d\n", StackEmpty(&ps));
printf("Size:%d\n", StackSize(&ps));
StackDestory(&ps);
}