Stack Data Structure in C (LIFO Operations)

Stacks in C — conceptual cover illustration
Stacks in C — conceptual cover illustration

A stack implements Last-In, First-Out (LIFO) semantics. Learn array-based stack implementation in C with push, pop, peek operations, and boundary safety guards.

A Stack is a Last-In, First-Out (LIFO) abstract data type where insertions (push) and deletions (pop) occur exclusively at one end, known as the top. Stacks are fundamental to compiler syntax parsing, expression evaluation, and recursion call stack management.

This implementation showcases an array-based stack in C. Array-backed stacks offer maximum cache locality and O(1) time complexity for push, pop, and peek operations.

Managing an array stack requires constant vigilance against two classic runtime errors: Stack Overflow (attempting to push onto a full stack) and Stack Underflow (attempting to pop from an empty stack).

Interactive Runnable C Implementation

#include <stdio.h>
#define MAX 100

typedef struct {
    int items[MAX];
    int top;
} Stack;

void initStack(Stack *s) { s->top = -1; }
int isFull(Stack *s) { return s->top == MAX - 1; }
int isEmpty(Stack *s) { return s->top == -1; }

void push(Stack *s, int val) {
    if (isFull(s)) {
        printf("Stack Overflow!\n");
        return;
    }
    s->items[++(s->top)] = val;
}

int pop(Stack *s) {
    if (isEmpty(s)) {
        printf("Stack Underflow!\n");
        return -1;
    }
    return s->items[(s->top)--];
}

int peek(Stack *s) {
    if (isEmpty(s)) return -1;
    return s->items[s->top];
}

int main() {
    Stack s;
    initStack(&s);
    push(&s, 10);
    push(&s, 20);
    push(&s, 30);

    printf("Top element: %d\n", peek(&s));
    printf("Popped: %d\n", pop(&s));
    printf("New top: %d\n", peek(&s));
    return 0;
}

Open example in compiler

Expected Output

Top element: 30
Popped: 30
New top: 20

Frequently Asked Questions

What is the time complexity of Stack Data Structure in C (LIFO)?

LIFO (Last-In First-Out) discipline with predictable asymptotic runtime behavior.

Related examples