C 语言栈粗浅学习记录
#include<stdio.h>
#include<stdlib.h>
typedef int type; //type 就是int
typedef struct Stack {
type* array;
size_t size;
size_t capacity;
}Stack;
void StackInit(Stack* sl, size_t n) {
sl->array = (type*)malloc(sizeof(type) * n); //分配数组地址
sl->capacity = n; //栈的总内存
sl->size = 0; //代表着栈的序号?
}
void StackPush(Stack* sl, type x) {
if (sl->size == sl->capacity) { // 内存不够
sl->capacity *= 2; //分配两倍内存
sl->array = (type*)realloc(sl->array, sl->capacity); //重新分配内存
}
sl->array[sl->size++] = x; //将数放入
}
void StackPop(Stack* sl) {
if (sl->size) {
sl->size--; //序号-1 ?
}
}
type StackTop(Stack* sl) {
return sl->array[sl->size - 1]; //返回栈顶元素
}
int StackEmpty(Stack* sl) {
if (sl->size == 0) { //判断是否为空
return 1;
}
return 0;
}
size_t StackSize(Stack* sl) {
return sl->size; //返回栈内元素数目
}
void StackDestory(Stack* sl) {
free(sl->array);
sl->array = NULL; //栈顶删除
sl->size = 0;
sl->capacity = 0;
}
int main() {
Stack sl;
StackInit(&sl, 10);
StackInit(&sl, 1);
StackPush(&sl, 2);
StackPush(&sl, 3);
StackPush(&sl, 4);
StackPush(&sl, 5);
int a = (int)StackSize(&sl);
printf("size=%d\n", a);
while (StackEmpty(&sl) != 1) {
printf("%d", StackTop(&sl));
StackPop(&sl);
}
printf("\n");
return 0;
}