实现栈
对于栈,一般来说系统栈区只有8mb的大小,如果要进行调用,一定会不够用,导致我们栈溢出。所以我们要在堆区实现栈。
栈
1.引入头文件
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int stacktype;//别名一下数据类型便于修改数据类型
2.首先建一个类型命名为stack类
struct stack
{
stacktype * a;
int top;
int capacity;
};
typedef struct stack stack;//别名一下struct stack
3.初始化函数
第一步:将int*a指向空
第二步:capacity与top置为0
void intitstack(stack* stack)
{
assert(stack);
stack->a = NULL;
stack->capacity = stack->top = 0;
}
4.释放清理空间函数
1.assert断言一下防止不存在地址
2.释放a的空间
3.置为空并且容量和栈顶置为0
void destorystack(stack*stack)
{
assert(stack);
free(stack->a);
stack->a = NULL;
stack->capacity = stack->top = 0;
}
5.入栈函数
1.assert断言
2.扩容防止空间不够
3.放入数据
void stackpush(stack* stack, stacktype e)
{
assert(stack);
if (stack->top == stack->capacity)
{
int newcapcity = stack->capacity == 0 ? 4 :( 2 * stack->capacity);
stacktype* tmp = (stacktype*)realloc(stack->a,newcapcity * sizeof(stacktype));
if (tmp == NULL)
{
printf("error");
return;
}
stack->a = tmp;
stack->capacity = newcapcity;
}
stack->a[stack->top++] = e;
}
6.判断是否空栈函数
运用bool,直接return栈顶是否是0。
bool isempty(stack* stack)
{
assert(stack);
return stack->top == 0;
}
7.出栈函数
直接--top,不需要置零,让栈顶往下压
void stackpop(stack* stack)
{
assert(stack);
assert(!isempty(stack));
--stack->top;
}
8.显示栈顶
1.top-1因为top指向栈顶,栈顶不存元素,
stacktype stacktop(stack*stack)
{
assert(stack);
return stack->a[stack->top - 1];
}
9.调试一下
插入三个元素再依次遍历一下
int main()
{
stack sta;
intitstack(&sta);
stackpush(&sta, 1);
stackpush(&sta, 2);
stackpush(&sta, 3);
while (!isempty(&sta))
{
printf("%d\n", stacktop(&sta));
stackpop(&sta);
}
return 0;
}
10.全部代码
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int stacktype;
struct stack
{
stacktype * a;
int top;
int capacity;
};
typedef struct stack stack;
bool isempty(stack* stack)
{
assert(stack);
return stack->top == 0;
}
void intitstack(stack* stack)
{
assert(stack);
stack->a = NULL;
stack->capacity = stack->top = 0;
}
void stackpush(stack* stack, stacktype e)
{
assert(stack);
if (stack->top == stack->capacity)
{
int newcapcity = stack->capacity == 0 ? 4 :( 2 * stack->capacity);
stacktype* tmp = (stacktype*)realloc(stack->a,newcapcity * sizeof(stacktype));
if (tmp == NULL)
{
printf("error");
return;
}
stack->a = tmp;
stack->capacity = newcapcity;
}
stack->a[stack->top++] = e;
}
void stackpop(stack* stack)
{
assert(stack);
assert(!isempty(stack));
--stack->top;
}
void destorystack(stack*stack)
{
assert(stack);
free(stack->a);
stack->a = NULL;
stack->capacity = stack->top = 0;
}
stacktype stacktop(stack*stack)
{
assert(stack);
return stack->a[stack->top - 1];
}
int main()
{
stack sta;
intitstack(&sta);
stackpush(&sta, 1);
stackpush(&sta, 2);
stackpush(&sta, 3);
while (!isempty(&sta))
{
printf("%d\n", stacktop(&sta));
stackpop(&sta);
}
return 0;
}