Implementing a stack in C programming involves creating a data structure that follows the Last In First Out (LIFO) principle. Here's a simple implementation of a stack using an array:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100 // Maximum size of the stack
// Structure to represent the stack
typedef struct {
int arr[MAX_SIZE];
int top; // Index of the top element
} Stack;
// Function to initialize the stack
void initialize(Stack *stack) {
stack->top = -1; // Initialize top as -1 to indicate an empty stack
}
// Function to check if the stack is empty
int isEmpty(Stack *stack) {
return (stack->top == -1); // If top is -1, stack is empty
}
// Function to check if the stack is full
int isFull(Stack *stack) {
return (stack->top == MAX_SIZE - 1); // If top reaches MAX_SIZE - 1, stack is full
}
// Function to push an element onto the stack
void push(Stack *stack, int data) {
if (isFull(stack)) {
printf("Stack overflow!\n");
return;
}
stack->arr[++stack->top] = data; // Increment top and add the element to the stack
}
// Function to pop an element from the stack
int pop(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack underflow!\n");
return -1;
}
return stack->arr[stack->top--]; // Return the top element and decrement top
}
// Function to peek at the top element of the stack without removing it
int peek(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty!\n");
return -1;
}
return stack->arr[stack->top]; // Return the top element
}
int main() {
Stack stack;
initialize(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
printf("Top element: %d\n", peek(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Top element: %d\n", peek(&stack));
return 0;
}
This implementation uses an array to store the elements of the stack and keeps track of the top element using an index (top
). The initialize, isEmpty, isFull, push, pop, and peek
functions provide the basic stack operations.
This code defines a stack using an array and provides functions for initialization, checking if the stack is empty or full, pushing elements onto the stack, popping elements from the stack, and peeking at the top element of the stack.