后進(jìn)先出(Last-In-First-Out,LIFO)的原則,入棧(Push):將元素插入到棧頂,出棧(Pop):從棧頂刪除元素,??梢允褂?strong>數(shù)組或鏈表實(shí)現(xiàn)。在實(shí)際應(yīng)用中,棧常常用于處理遞歸、括號(hào)匹配、表達(dá)式求值等場(chǎng)景。
#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;
}