一种元素后进先出(LIFO)的数据结构
代码实现:
#include <stdio.h>
#include <stdlib.h>
#define elem_type int // 宏定义 data 类型
//构建节点结构体
typedef struct Node{
struct Node* next;
elem_type data;
}Node;
//构建栈结构体
typedef struct Stack{
Node* head;
int size;
}Stack;
// 初始化
void init(Stack* stack){
stack->head = NULL;
stack->size = 0;
}
// 销毁栈
void destory(Stack* stack){
while(stack->head){
Node* temp = stack->head->next;
free(stack->head);
stack->head = temp;
}
stack->size = 0;
}
// 元素入栈
void push(Stack* stack, elem_type element){
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = element;
temp->next = stack->head;
stack->head = temp;
stack->size++;
}
// 弹出栈顶元素
elem_type pop(Stack* stack){
if (stack->size == 0){
printf("The stack is empty!\n");
exit(1);
}
else{
Node* temp = stack->head->next;
elem_type result = stack->head->data;
free(stack->head);
stack->head = temp;
stack->size--;
return result;
}
}
// 获取栈内元素个数
int len(Stack* stack){
return stack->size;
}
// 获取栈顶元素
elem_type top(Stack* stack){
if (stack->size == 0){
printf("The stack is empty!\n");
exit(1);
}
return stack->head->data;
}
int main(){
Stack stack;
init(&stack);
push(&stack,0);
push(&stack,1);
push(&stack,2);
push(&stack,3);
push(&stack,4);
printf("%d\n",pop(&stack));
printf("%d\n",pop(&stack));
printf("%d\n",top(&stack));
printf("%d\n",len(&stack));
destory(&stack);
printf("%d\n",len(&stack));
return 0;
}