Linked Lists & Stacks
Data structures in C are built from scratch using structs and pointers. Unlike higher-level languages with built-in collections, C requires manual memory management for every node, making it the best language to deeply understand how data structures work.
45 min•By Priygop Team•Last updated: Feb 2026
Data Structure Code
Example
#include <stdio.h>
#include <stdlib.h>
// Singly linked list
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createNode(int data) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
return node;
}
void insertFront(Node **head, int data) {
Node *newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
void printList(Node *head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
void freeList(Node *head) {
while (head) {
Node *temp = head;
head = head->next;
free(temp);
}
}
// Stack (array-based)
typedef struct {
int *data;
int top;
int capacity;
} Stack;
Stack *createStack(int capacity) {
Stack *s = (Stack *)malloc(sizeof(Stack));
s->data = (int *)malloc(capacity * sizeof(int));
s->top = -1;
s->capacity = capacity;
return s;
}
void push(Stack *s, int value) {
if (s->top >= s->capacity - 1) return; // Overflow
s->data[++(s->top)] = value;
}
int pop(Stack *s) {
if (s->top < 0) return -1; // Underflow
return s->data[(s->top)--];
}
int main() {
// Linked list usage
Node *list = NULL;
insertFront(&list, 30);
insertFront(&list, 20);
insertFront(&list, 10);
printList(list); // 10 -> 20 -> 30 -> NULL
freeList(list);
// Stack usage
Stack *stack = createStack(10);
push(stack, 1); push(stack, 2); push(stack, 3);
printf("Pop: %d\n", pop(stack)); // 3 (LIFO)
free(stack->data); free(stack);
return 0;
}