头文件
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
封装栈结构
typedef struct Data {
int data;
}*LPDATA;
typedef struct Stack {
LPDATA pMemory;
int topPos;
}*LPSTACK;
初始化栈
LPSTACK CreateStack() {
LPSTACK stack = (LPSTACK)calloc(1, sizeof(Stack));
assert(stack);
stack->pMemory = (LPDATA)calloc(MAX, sizeof(Data));
assert(stack->pMemory);
stack->topPos = -1;
return stack;
}
入栈
void Push(LPSTACK stack,int Mydata) {
if (stack->topPos+1== MAX)
return;
stack->pMemory[++stack->topPos].data = Mydata;
}
出栈
void Pop(LPSTACK stack) {
if (stack->topPos == -1)
return;
stack->topPos--;
}
获取栈顶元素
int top(LPSTACK stack) {
return stack->pMemory[stack->topPos].data;
}
判断栈是否为空
bool temp(LPSTACK stack) {
return stack->topPos == -1;
}
测试代码
int main() {
LPSTACK stack = CreateStack();
printf("入栈:\t");
for (int i = 0; i < 10; i++) {
printf("%d\t", i);
Push(stack, i);
}
printf("\n");
printf("出栈:\t");
while (!temp(stack)) {
printf("%d\t", top(stack));
Pop(stack);
}
return 0;
}
效果