A linked list stack allocates memory for each new element dynamically, so it can grow or shrink as needed. An array stack allocates a fixed block of memory upfront, which may be larger than needed or limit growth.
int stack[5]; int top = -1; void push(int x) { if (top < 4) { top++; stack[top] = x; } } void printStack() { for (int i = top; i >= 0; i--) { printf("%d -> ", stack[i]); } printf("null\n"); } int main() { push(10); push(20); push(30); printStack(); return 0; }
The stack follows Last-In-First-Out (LIFO). The last pushed element (30) is printed first, then 20, then 10.
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* top = NULL;
void push(int x) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = x;
newNode->next = top;
top = newNode;
}
void pop() {
if (top != NULL) {
Node* temp = top;
top = top->next;
free(temp);
}
}
void printStack() {
Node* temp = top;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("null\n");
}
int main() {
push(5);
push(15);
pop();
push(25);
printStack();
return 0;
}Push 5: stack is 5 -> null.
Push 15: stack is 15 -> 5 -> null.
Pop removes 15, stack is 5 -> null.
Push 25: stack is 25 -> 5 -> null.
Both implementations add or remove elements only at the top, so push and pop are constant time operations (O(1)) in both cases.
Real-time systems require predictable timing and memory usage. Array stacks allocate fixed memory upfront, avoiding unpredictable delays from dynamic memory allocation used in linked lists.
