后进先出(Last-In-First-Out,LIFO)的原则,入栈(Push):将元素插入到栈顶,出栈(Pop):从栈顶删除元素,栈可以使用数组或链表实现。在实际应用中,栈常常用于处理递归、括号匹配、表达式求值等场景。
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
void initialize(Stack* stack) {
stack->top = -1;
}
void push(Stack* stack, int item) {
if (stack->top == MAX_SIZE - 1) {
printf("Stack is full. Cannot push element.\n");
return;
}
stack->data[++stack->top] = item;
}
int pop(Stack* stack) {
if (stack->top == -1) {
printf("Stack is empty. Cannot pop element.\n");
return -1;
}
return stack->data[stack->top--];
}
int peek(Stack* stack) {
if (stack->top == -1) {
printf("Stack is empty.\n");
return -1;
}
return stack->data[stack->top];
}
int isEmpty(Stack* stack) {
return stack->top == -1;
}
int size(Stack* stack) {
return stack->top + 1;
}
int main() {
Stack stack;
initialize(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
printf("Stack size: %d\n", size(&stack));
printf("Top element: %d\n", peek(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Stack size: %d\n", size(&stack));
return 0;
}