数组栈的实现
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
/*
1. 栈容量
2. 栈顶标记
3. FILO
*/
typedef struct {
int* stackMemory; //栈容量
int stackTop; //栈顶标记
int maxSize; //栈最大元素个数
}STACK,*LPSTACK;
//创建栈
LPSTACK createStack() {
LPSTACK stack = (LPSTACK)malloc(sizeof(STACK));
if (NULL == stack) {
printf("数组栈内存申请失败!\n");
return NULL;
}
stack->stackMemory = (int*)malloc(sizeof(int) * MAX);
if (stack->stackMemory == NULL) {
printf("数组栈数组内存申请失败!\n");
free(stack);
stack = NULL;
return NULL;
}
stack->stackTop = -1;
stack->maxSize = MAX;
return stack;
}
//内存扩容
void realStack(LPSTACK stack) {
if (stack == NULL)
return;
stack->maxSize += 10;
int* p = (int*)realloc(stack->stackMemory, stack->maxSize * sizeof(int));
if (p == NULL) {
printf("内存扩容失败!\n");
}
else {
stack->stackMemory = p;
}
}
//入栈
void push(LPSTACK stack, int data) {
if (stack == NULL) {
printf("栈不存在,入栈失败!\n");
return;
}
if (stack->stackTop >= stack->maxSize - 1) {
printf("栈满,已扩容!\n");
realStack(stack);
}
stack->stackMemory[++stack->stackTop] = data;
}
//出栈
void pop(LPSTACK stack) {
if (stack != NULL && stack->stackTop != -1) {
stack->stackTop--;
}
else { //栈空
printf("栈空,无元素可出栈!\n");
return;
}
}
//返回栈顶元素
int top(LPSTACK stack) {
return stack->stackMemory[stack->stackTop];
}
//通过指针方式获取栈顶元素
void getStackTopElement(LPSTACK stack, int* data) {
*data = stack->stackMemory[stack->stackTop];
}
//万金油函数
int empty(LPSTACK stack) {
return stack->stackTop == -1;
}
int size(LPSTACK stack) {
return stack->stackTop + 1;
}
//销毁栈
void destroyStack(LPSTACK* stack) {
if (*stack != NULL) {
free((*stack)->stackMemory);
(*stack)->stackMemory = NULL;
free(*stack);
*stack = NULL;
}
}
int main()
{
LPSTACK stack = createStack();
//入栈操作
for (int i = 0; i < 40; i++)
{
push(stack, i);
}
printf("size:%d,top: %d\n", size(stack),stack->stackTop);
//出栈打印操作
while (!empty(stack)) {
printf("%d\t", top(stack));
pop(stack);
}
putchar('\n');
printf("size:%d,top: %d\n", size(stack), stack->stackTop);
destroyStack(&stack);
if (stack == NULL) {
printf("栈销毁成功!\n");
}
return 0;
}