堆疊是一種線性資料結構,遵循後進先出 (LIFO) 原則,也稱為先進後出 (FILO)。這表示新增至堆疊的最後一個元素是第一個要移除的元素。它的運作方式就像一堆實體物品,例如盤子或書籍,您只能在頂部新增或刪除物品。
在 C 語言裡可以使用陣列(array)或鏈結串列(linked list) 來實作 stack
#include <stdio.h>
#include <stdlib.h> // For malloc and free
#include <limits.h> // For INT_MIN
// A structure to represent a stack
struct Stack {
int top;
unsigned capacity;
int* array;
};
// Function to create a stack of given capacity.
struct Stack* createStack(unsigned capacity) {
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
if (!stack) {
return NULL;
}
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(stack->capacity * sizeof(int));
if (!stack->array) {
free(stack);
return NULL;
}
return stack;
}
int isFull(struct Stack* stack) {
return stack->top == stack->capacity - 1;
}
int isEmpty(struct Stack* stack) {
return stack->top == -1;
}
void push(struct Stack* stack, int item) {
if (isFull(stack)) {
printf("Stack Overflow\n");
return;
}
stack->array[++stack->top] = item;
printf("%d pushed to stack\n", item);
}
int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow\n");
return INT_MIN;
}
return stack->array[stack->top--];
}
int peek(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return INT_MIN;
}
return stack->array[stack->top];
}
void freeStack(struct Stack* stack) {
if (stack) {
free(stack->array);
free(stack);
}
}
int main() {
struct Stack* stack = createStack(5);
if (!stack) {
printf("Failed to create stack.\n");
return 1;
}
push(stack, 10);
push(stack, 20);
push(stack, 30);
printf("\nTop element is %d\n", peek(stack));
printf("%d popped from stack\n", pop(stack));
printf("After popping, top element is %d\n\n", peek(stack));
push(stack, 40);
push(stack, 50);
push(stack, 60);
push(stack, 70); // This will cause a stack overflow
printf("\nPopping all elements:\n");
while(!isEmpty(stack)) {
printf("%d popped from stack\n", pop(stack));
}
pop(stack); // This will cause a stack underflow
freeStack(stack);
return 0;
}