提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前期准备
1.头文件
#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;//栈顶
int capacity;//容量
}ST;
//初始化
void StackInit(ST* ps);
//销毁
void StackDestory(ST* ps);
//入栈
void StackPush(ST* ps, STDataType x);
//出栈
void StackPop(ST* ps);
//栈顶元素
STDataType StackTop(ST* ps);
//元素个数
int StackSize(ST* ps);
//判空
bool StackEmpty(ST* ps);
1.初始化
//初始化
void StackInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
2.销毁
//销毁
void StackDestory(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
一、入栈和出栈
1.入栈
//入栈
void StackPush(ST* ps, STDataType x)
{
assert(ps);
if (ps->capacity == ps->top)//判断容量是否为满
{
int newnode = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (STDataType*)realloc(ps->a,sizeof(STDataType)*newnode);
if (tmp == NULL)
{
printf("realloc fail");
exit(-1);
}
ps->capacity = newnode;
ps->a = tmp;
}
ps->a[ps->top] = x;
ps->top++;
}
2.出栈
//出栈
void StackPop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));//断言看是否为空
ps->top--;
}
在这里插入代码片
二、栈顶元素、元素个数和判空
1.栈顶元素
//栈顶元素
STDataType StackTop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));//断言看是否为空
return ps->a[ps->top-1];
}
2.元素个数
//元素个数
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
3.判空
//判空
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
三、实现
void test()
{
ST s;
StackInit(&s);
StackPush(&s, 1);
StackPush(&s, 2);
StackPush(&s, 3);
printf("%d ", StackTop(&s));
StackPop(&s);
StackPush(&s, 4);
StackPush(&s, 5);
while (!StackEmpty(&s))
{
printf("%d ", StackTop(&s));
StackPop(&s);
}
StackDestory(&s);
}
int main()
{
test();
return 0;
}
总结
以上为栈的实现的全部内容。