Introduction to Data Structures in C
A program is only as good as the way it stores its data. A phone's contact list, a printer's job line, the "undo" button and Google Maps routes all use a different way of organising data. Each of these ways is called a data structure.
In this lesson you will learn what a data structure is, the difference between linear and non-linear structures, the main types (array, linked list, stack, queue, tree, graph, hash table), the basic operations and the Big-O idea used to compare them. The rest of this module builds each one in C.
What You Will Learn
- What a data structure and an abstract data type (ADT) are.
- Primitive vs non-primitive, linear vs non-linear structures.
- Where each common data structure is used in real life.
- The basic operations: traverse, insert, delete, search, sort.
- How Big-O notation describes speed.
- Why C programs build data structures with structs and pointers.
Introduction to Data Structures in C Explained
Exam definition: A data structure is a particular way of organising and storing data in memory so that it can be accessed and modified efficiently. Data structures are classified as primitive (int, char, float, pointers) and non-primitive; non-primitive structures are either linear (elements form a sequence: array, linked list, stack, queue) or non-linear (elements form a hierarchy or network: tree, graph). An abstract data type (ADT) describes what operations a structure supports, not how they are implemented.
Memory trick: Data structures are ways of arranging things at home. A shoe rack with numbered slots = array. A train of coaches joined by hooks = linked list. A pile of plates = stack (last in, first out). A ticket queue = queue (first in, first out). A family tree = tree. A city road map = graph. A labelled cupboard where you jump straight to "Socks" = hash table.
Classification of data structures
Data Structures
├── Primitive: int, char, float, double, pointer
└── Non-primitive
├── Linear (one after another)
│ ├── Array
│ ├── Linked list (singly, doubly, circular)
│ ├── Stack (LIFO)
│ └── Queue (FIFO), circular queue
└── Non-linear (hierarchy / network)
├── Tree (binary tree, binary search tree)
└── Graph
(Hash table: array + hash function, used for fast lookup)
Syntax: Building Blocks in C
C has no built-in list, stack or tree. You build them from arrays, structures and pointers, using malloc for memory:
int marks[100]; /* array: fixed size, index access */
struct node /* a "node" for linked structures */
{
int data; /* the value stored */
struct node *next; /* link to the next node */
};
struct node *n = malloc(sizeof *n); /* create a node at run time */
n->data = 10;
n->next = NULL; /* NULL = end of the chain */
| Structure | Rule | Real-life use |
|---|---|---|
| Array | Fixed size, direct access by index | Marks of 60 students, image pixels |
| Linked list | Nodes joined by pointers; grows and shrinks | Music playlist, browser history |
| Stack | Last In, First Out (LIFO) | Undo/redo, function calls, bracket checking |
| Queue | First In, First Out (FIFO) | Printer jobs, CPU scheduling, ticket booking |
| Tree | Parent–child hierarchy | Folders on a disk, family tree, database indexes |
| Graph | Nodes connected by edges | Maps and routes, social networks |
| Hash table | Key → slot by a hash function | Dictionaries, login lookup, caches |
Example 1: The Same Data in an Array and a Linked List
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main(void)
{
int arr[3] = {10, 20, 30};
struct node *head = NULL, *n, *p;
int i;
/* Build the list 10 -> 20 -> 30 by adding at the front, from the end */
for (i = 2; i >= 0; i--)
{
n = malloc(sizeof *n);
if (n == NULL)
return 1;
n->data = arr[i];
n->next = head;
head = n;
}
printf("Array : ");
for (i = 0; i < 3; i++)
printf("%d ", arr[i]);
printf("\narr[2] : %d (direct access)\n", arr[2]);
printf("Linked list: ");
for (p = head; p != NULL; p = p->next)
printf("%d -> ", p->data);
printf("NULL\n");
printf("3rd node : %d (reached by following 2 links)\n", head->next->next->data);
while (head != NULL) /* free every node */
{
n = head->next;
free(head);
head = n;
}
return 0;
}
Output
Array : 10 20 30 arr[2] : 30 (direct access) Linked list: 10 -> 20 -> 30 -> NULL 3rd node : 30 (reached by following 2 links)
Code Explanation
- The array stores the three values side by side in one block.
arr[2]jumps straight to the third value: direct (random) access. - Each linked-list node is a separate block created by
malloc, holding a value and a pointer to the next node. - Adding at the front (
n->next = head; head = n;) from the last value to the first builds 10 → 20 → 30. - To reach the third node, the program must follow links:
head->next->next. This is sequential access. - The final loop frees every node; otherwise the memory would leak.
How We Compare Data Structures: Big-O
Time complexity describes how the number of steps grows as the number of elements n grows. It is written in Big-O notation:
| Big-O | Name | Steps for n = 1,000 | Example |
|---|---|---|---|
| O(1) | Constant | 1 | Array access arr[i] |
| O(log n) | Logarithmic | about 10 | Binary search |
| O(n) | Linear | 1,000 | Linear search, traversing a list |
| O(n log n) | Linearithmic | about 10,000 | Merge sort |
| O(n²) | Quadratic | 1,000,000 | Bubble sort |
Array vs linked list
| Operation | Array | Linked list |
|---|---|---|
| Access the i-th element | O(1) | O(n) |
| Insert/delete at the beginning | O(n) (shift elements) | O(1) |
| Size | Fixed (unless reallocated) | Grows and shrinks freely |
| Extra memory | None | One pointer per node |
| Memory layout | One continuous block | Nodes scattered in memory |
Example 2: Counting Steps for Linear vs Binary Search
#include <stdio.h>
int linear_steps(const int a[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (a[i] == key)
return i + 1; /* comparisons made */
return n;
}
int binary_steps(const int a[], int n, int key)
{
int low = 0, high = n - 1, steps = 0, mid;
while (low <= high)
{
mid = (low + high) / 2;
steps++;
if (a[mid] == key)
return steps;
if (a[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return steps;
}
int main(void)
{
static int a[1000];
int i;
for (i = 0; i < 1000; i++)
a[i] = i * 2; /* sorted: 0, 2, 4, ..., 1998 */
printf("Search 1998 in 1000 sorted numbers\n");
printf("Linear search steps: %d\n", linear_steps(a, 1000, 1998));
printf("Binary search steps: %d\n", binary_steps(a, 1000, 1998));
return 0;
}
Output
Search 1998 in 1000 sorted numbers Linear search steps: 1000 Binary search steps: 10
- Linear search checks every element: O(n), here 1000 comparisons.
- Binary search halves the range each time: O(log n), here only 10 comparisons.
- Choosing the right data structure and algorithm can make a program 100 times faster without a faster computer. (Both searches are explained in Linear and Binary Search in C.)
Important Points to Remember
- A data structure = a way to organise data for efficient access and change.
- Linear: array, linked list, stack, queue. Non-linear: tree, graph.
- Stack = LIFO, Queue = FIFO.
- Arrays give O(1) access but fixed size; linked lists give cheap insert/delete but O(n) access.
- Basic operations: traverse, insert, delete, search, sort.
- In C, data structures are built from structs, pointers and malloc; always free what you allocate.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
| Calling a stack "FIFO" | Wrong exam answer | Stack = LIFO, queue = FIFO |
Using a linked list when you need a[i] often | Slow O(n) access every time | Use an array for index access |
Forgetting next = NULL on the last node | Traversal runs into garbage | Always end the chain with NULL |
| Not freeing nodes | Memory leak | Free every node before exit |
| Binary search on unsorted data | Wrong results | Sort first, or use linear search |
Data Structures Practice Questions
- What is a data structure? Why do we need it?
- Differentiate between linear and non-linear data structures with examples.
- What is an abstract data type?
- Compare an array and a linked list on access, insertion and memory.
- What does O(log n) mean? Give an example.
Show answers
- A way of organising and storing data so it can be used efficiently; the right structure makes operations faster and code simpler.
- Linear: elements in a sequence (array, linked list, stack, queue). Non-linear: hierarchy or network (tree, graph).
- A description of a data type by its operations (what it does), independent of its implementation; e.g. a Stack ADT has push, pop and peek.
- Array: O(1) access, costly insert/delete, fixed contiguous memory. Linked list: O(n) access, O(1) insert/delete at a known spot, dynamic size, extra pointer per node.
- Steps grow with the logarithm of n, i.e. the problem is halved each step; binary search.
Coding Exercise
Using struct node, build a linked list of the numbers 5, 15, 25, 35 (in that order), print it, print the number of nodes and their sum, then free all nodes.
Show solution
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main(void)
{
int values[] = {5, 15, 25, 35};
struct node *head = NULL, *tail = NULL, *n, *p;
int i, count = 0, sum = 0;
for (i = 0; i < 4; i++) /* add at the end, using a tail pointer */
{
n = malloc(sizeof *n);
if (n == NULL)
return 1;
n->data = values[i];
n->next = NULL;
if (head == NULL)
head = n;
else
tail->next = n;
tail = n;
}
for (p = head; p != NULL; p = p->next)
{
printf("%d ", p->data);
count++;
sum += p->data;
}
printf("\nNodes: %d, Sum: %d\n", count, sum);
while (head != NULL)
{
n = head->next;
free(head);
head = n;
}
return 0;
}
5 15 25 35 Nodes: 4, Sum: 80
Quick Quiz: Data Structures (MCQ)
-
Which is a non-linear data structure?
A) Stack B) Queue C) Tree D) Array
-
A stack works on the principle:
A) FIFO B) LIFO C) Random D) Sorted order
-
Accessing the 50th element of an array takes:
A) O(1) B) O(n) C) O(log n) D) O(n²)
-
Which structure best represents a road map?
A) Queue B) Graph C) Stack D) Array
-
The time complexity of binary search is:
A) O(n) B) O(n²) C) O(log n) D) O(1)
Show answers
- C: tree.
- B: LIFO.
- A: O(1).
- B: graph.
- C: O(log n).
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Data structure | Way to organise data for efficient use |
|---|---|
| Linear | Array, linked list, stack, queue |
| Non-linear | Tree, graph |
| Stack / Queue | LIFO / FIFO |
| ADT | Defined by its operations, not implementation |
| Array access | O(1); list access O(n) |
| Binary search | O(log n), needs sorted data |
Frequently asked questions
- What is a data structure in C?
- A way of storing and organising data (built with arrays, structs and pointers) so that it can be accessed and modified efficiently.
- What are the types of data structures?
- Primitive and non-primitive; non-primitive are linear (array, list, stack, queue) and non-linear (tree, graph).
- When should you use a linked list instead of an array?
- When the size changes often and you insert/delete a lot, but rarely need access by index.
Remember
- Rack, train, plates, queue, family tree, road map, labelled cupboard.
- Pick the structure for the operation you do most.
Next Topic
Next lesson: Singly Linked List in C. You will build a singly linked list and write insert, delete, search and display functions.