栈的特点
先进后出,后进先出
栈的实现
stackqueue.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int DataType;
typedef struct STQ
{
DataType* a;//相当于创建一个数组
int top;
int capacity;
}STQ;
//先进后出
//后进先出
//
//
//初始化
void Init(STQ* ps);
//压栈
void Push(STQ* ps, DataType data);
//出栈
void Pop(STQ* ps);
//返回top的值
DataType ShowTop(STQ* ps);
//销毁
void Distory(STQ* ps);
//判断是否空了
_Bool Empty(STQ* ps);
//出栈展示
void Show(STQ* ps);
stackqueue.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"StackQueue.h"
void Init(STQ* ps)
{
assert(ps);
ps->a = NULL;
ps->capacity = 0;
ps->top = 0;
}
void Push(STQ* ps, DataType data)
{
if (ps->top==ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;//三目操作符
DataType* tmp = (DataType*)realloc(ps->a, newcapacity * sizeof(int));
if (tmp == NULL)
{
perror("realoc:");
exit(-1);
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = data;
ps->top++;
}
void Pop(STQ* ps)
{
assert(ps);
assert(ps->top > 0);
ps->top--;
}
DataType ShowTop(STQ* ps)
{
assert(ps);
assert(!Empty(ps));
return ps->a[ps->top];
}
void Distory(STQ* ps)
{
assert(ps);
free(ps->a);
ps->capacity = ps->top = 0;
}
_Bool Empty(STQ* ps)
{
return ps->top == 0;
}
void Show(STQ* ps)
{
assert(ps);
while (!Empty(ps))
{
printf("%d ", ps->a[ps->top-1]);
Pop(ps);
}
}
satcktest.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"StackQueue.h"
void test1()
{
STQ stack;
Init(&stack);
Push(&stack, 1);
Push(&stack, 2);
Push(&stack, 3);
Show(&stack);
Distory(&stack);
}
int main()
{
test1();
return 0;
}