C Language
14. Data Structures & AlgorithmsAdvanced14 min read

Data Structures in C: Linked Lists, Stacks & Queues

Implement fundamental data structures from scratch in C: Singly Linked Lists, Stacks, Queues, and Binary Search Trees.

Key Takeaways & Core Concepts
  • A Linked List is a linear data structure where elements (nodes) are dynamically linked via pointers.
  • Unlike arrays, linked lists allow dynamic sizing and $O(1)$ insertion/deletion at the head without memory reallocations.
  • A Stack is a LIFO (Last-In, First-Out) structure supporting push, pop, and peek.
  • A Queue is a FIFO (First-In, First-Out) structure supporting enqueue and dequeue.
  • Always traverse and free every dynamically allocated node to avoid memory leaks.

Singly Linked List Implementation

Each node contains data and a pointer to the next node:

C Code Example
1typedef struct Node {
2 int data;
3 struct Node *next;
4} Node;
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
4 lines
Singly Linked List Operations (Insert at Head & Traversal)
1#include <stdio.h>
2#include <stdlib.h>
3
4typedef struct Node {
5 int data;
6 struct Node *next;
7} Node;
8
9void insertHead(Node **headRef, int value) {
10 Node *newNode = (Node*)malloc(sizeof(Node));
11 newNode->data = value;
12 newNode->next = *headRef;
13 *headRef = newNode;
14}
15
16void printList(const Node *head) {
17 const Node *curr = head;
18 while (curr != NULL) {
19 printf("%d -> ", curr->data);
20 curr = curr->next;
21 }
22 printf("NULL\n");
23}
24
25void freeList(Node *head) {
26 Node *curr = head;
27 while (curr != NULL) {
28 Node *temp = curr->next;
29 free(curr);
30 curr = temp;
31 }
32}
33
34int main(void) {
35 Node *head = NULL;
36
37 insertHead(&head, 30);
38 insertHead(&head, 20);
39 insertHead(&head, 10);
40
41 printf("Constructed Linked List:\n");
42 printList(head);
43
44 freeList(head);
45 head = NULL;
46 printf("Linked list nodes cleanly freed from Heap.\n");
47
48 return 0;
49}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
49 lines
Note: insertHead takes a double pointer (Node **headRef) so it can mutate the caller's head variable directly.
Practice & AssessmentC Programming Complete Course

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 1 correct(0 attempted)

1

What is the time complexity of inserting a node at the head of a singly linked list?

Beginner