栈的实现
栈:只能在栈顶插入,栈顶删除的一种数据结构,后进先出
栈是一种很重要的数据结构,尤其当实现某种功能时用到了递归,但有时递归调用过多会导致栈(此栈为计算机内存的栈,非数据结构的栈)溢出,或者效率太低,这时就可利用栈和循环模拟递归实现该功能,从而解决上述问题.
//该栈还有待优化
//头文件
#define _CRT_SECURE_NO_WARNINGS
#define _warn_unused_result
#pragma warning(disable:4996)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<malloc.h>
typedef int STDataType;
typedef struct Stack {
STDataType* _a;
int _top; // 栈顶
int _capacity; // 容量
}Stack;
//初始化
void StackInit(Stack* ps);
//销毁
void StackDestory(Stack* ps);
//入栈
void StackPush(Stack* ps, STDataType x);
//出栈
void StackPop(Stack* ps);
//获得栈顶元素
STDataType StackTop(Stack* ps);
//判断栈是否为空
int StackEmpty(Stack* ps);
//返回栈的实际元素大小
int StackSize(Stack* ps);
//测试函数
void TestStack();
//输出函数
void print_stack(Stack* ps);
//c文件
#include"stack.h"
void StackInit(Stack* ps) {
assert(ps);
ps->_capacity = 3;
ps->_top = 0;
Stack* tmp = (Stack*)malloc(ps->_capacity * sizeof(Stack));
ps->_a = tmp;
}
void StackDestory(Stack* ps) {
assert(ps);
ps->_a = NULL;
ps->_capacity = 0;
ps->_top = 0;
return 0;
}
void StackPush(Stack* ps, STDataType x) {
assert(ps);
if (ps->_capacity == ps->_top) {
Stack* tmp = (Stack*)malloc((ps->_capacity + 2) * sizeof(Stack));
if (tmp!=NULL) {
for (int i = 0; i < ps->_capacity; i++) {
//tmp->_a[i] = ps->_a[i];
tmp[i] = ps[i];
}
//free(ps);
ps= tmp;
ps->_capacity += 2;
}else {
printf("%s\n", strerror(errno));
return;
}
}
ps->_a[ps->_top] = x;
ps->_top++;
}
void StackPop(Stack* ps) {
assert(ps);
if (StackEmpty(ps) == 1) {
printf("栈为空\n");
return;
}else {
ps->_top--;
}
}
STDataType StackTop(Stack* ps) {
if (StackEmpty(ps) == 1) {
printf("栈为空\n");
return NULL;
}else {
return ps->_a[ps->_top-1];
}
}
int StackEmpty(Stack* ps) {
assert(ps);
if (ps->_top == 0) {
return 1;
}
return 0;
}
int StackSize(Stack* ps) {
return ps->_top;
}
void print_stack(Stack* ps) {
assert(ps);
if (StackEmpty(ps) == 1) {
printf("栈为空\n");
return NULL;
}else {
for (int i = 0; i < ps->_top; i++) {
printf("%d ", ps->_a[i]);
}
printf("\n");
}
}
void TestStack(){
Stack ps;
StackInit(&ps);
StackPush(&ps, 0);
StackPush(&ps, 1);
StackPush(&ps, 2);
print_stack(&ps);
StackPop(&ps);
print_stack(&ps);
StackPush(&ps, 3);
StackPush(&ps, 4);
print_stack(&ps);
StackPop(&ps);
print_stack(&ps);
}
int main() {
TestStack();
}