Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
Module 2 · syllabusAsked 9× in KTU papersLesson live

Singly linked lists and their operations

Nodes that point to the next node: create, traverse, count, find the largest, insert, delete, search and append.

Syllabus says: “Singly Linked List - Operations on Linked List”

On this page · 16 sections
ormakkurippu ✎
Never-forget card

Every node = DATA + ADDRESS of the next. Lose the head, lose the whole list. Always LINK FIRST, then MOVE the head.

Picture it

A treasure hunt at a college fest: each clue (node) has a prize (data) and tells you where the next clue is hidden (link). The last clue says ‘THE END’ (NULL).

Write this in the exam

A singly linked list is a sequence of nodes where each node holds data and a pointer to the next node; the last node's pointer is NULL and the list is accessed through a head pointer.

തല (head) പോയാൽ ലിസ്റ്റ് മുഴുവൻ പോയി!

What you will be able to do

  • Define a self-referential structure with an example.
  • Write algorithms to traverse, count and find the largest element.
  • Insert at the beginning, at the end and after a given node; delete a node; search.
  • Append (concatenate) two lists; count occurrences of a word.
  • Compare arrays and linked lists.

The story

Arrays are like a row of theatre seats: fixed in number and side by side. To fit a friend in the middle, everyone has to shift. A linked list is like friends spread across the hall, each holding a note saying where the next friend sits. Adding someone new just means changing one note.

Self-referential structure and the node

Definition

A self-referential structure is a structure that contains a pointer to a structure of the same type. It is the building block of linked lists and trees.

C
struct node {
    int data;              /* the information */
    struct node *link;     /* address of the next node (self-reference) */
};
struct node *head = NULL;  /* empty list */

struct node *getNode(int x) {
    struct node *p = malloc(sizeof(struct node));
    if (p == NULL) { printf("Out of memory\n"); exit(1); }
    p->data = x;  p->link = NULL;
    return p;
}
head1025742NULL
A singly linked list with 4 nodes; the last link is NULL.

Worked example

head25742NULL
Before: head → 25.
head1025742NULL
After new→link ← head and head ← new: head → 10 → 25 → …

Now watch it run

Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶.

Loading visualizer…

The algorithms KTU asks

Traverse / count (May 2026 Q4) / largest (Nov 2025 Q4)

algorithm
Algorithm CountAndMax(head)
1. if head = NULL then print "List empty"; return
2. count ← 0;  max ← head→data;  p ← head
3. while p ≠ NULL do
4.     count ← count + 1
5.     if p→data > max then max ← p→data
6.     p ← p→link
7. print count, max

Insert at the beginning and at the end (model paper Q12b)

algorithm
Algorithm InsertFront(x)
1. new ← getNode(x)
2. new→link ← head          // link first …
3. head ← new               // … then move head

Algorithm InsertEnd(x)
1. new ← getNode(x)          // new→link = NULL
2. if head = NULL then head ← new; return
3. p ← head
4. while p→link ≠ NULL do p ← p→link
5. p→link ← new

Insert after a given node, delete a value

algorithm
Algorithm InsertAfter(q, x)        // q points to an existing node
1. new ← getNode(x)
2. new→link ← q→link
3. q→link ← new

Algorithm Delete(key)
1. if head = NULL then print "Underflow"; return
2. if head→data = key then t ← head; head ← head→link; free(t); return
3. prev ← head; p ← head→link
4. while p ≠ NULL and p→data ≠ key do prev ← p; p ← p→link
5. if p = NULL then print "Not found"; return
6. prev→link ← p→link;  free(p)

Append one list to another (May 2026 Q12b) and count a word (model paper Q4)

algorithm
Algorithm Append(head1, head2)
1. if head1 = NULL then return head2
2. p ← head1
3. while p→link ≠ NULL do p ← p→link
4. p→link ← head2
5. return head1

Algorithm CountWord(head, w)
1. count ← 0; p ← head
2. while p ≠ NULL do
3.     if strcmp(p→word, w) = 0 then count ← count + 1
4.     p ← p→link
5. return count

C implementation

singly_linked_list.ctested ✓ 160/160 cases
C
/* Singly linked list — KTU PCCST303, Module 2
 * struct node is self-referential: each node stores data and a pointer to the next node.
 * Commands (one per line, until EOF):
 *   IF x  insert at front      IE x  insert at end      IA k x  insert x after key k
 *   D x   delete first x       S x   search x           R       reverse in place
 *   T     traverse: count the nodes and find the largest element (KTU Nov 2025 Q4, May 2026 Q4)
 * After every command: an optional result line, then "LIST: ..." (first → last).          */
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};
struct node *head = NULL;

struct node *getNode(int x) {
    struct node *n = malloc(sizeof *n);
    if (n == NULL) { printf("OUT OF MEMORY\n"); exit(1); }
    n->data = x;
    n->next = NULL;
    return n;
}

void insertFront(int x) {
    struct node *n = getNode(x);
    n->next = head;          /* new node points to the old first node ... */
    head = n;                /* ... then head moves to the new node       */
}

void insertEnd(int x) {
    struct node *n = getNode(x), *p;
    if (head == NULL) { head = n; return; }
    p = head;
    while (p->next != NULL) p = p->next;   /* walk to the last node */
    p->next = n;
}

void insertAfter(int key, int x) {
    struct node *p = head, *n;
    while (p != NULL && p->data != key) p = p->next;
    if (p == NULL) { printf("key %d not found\n", key); return; }
    n = getNode(x);
    n->next = p->next;       /* order matters: link the new node first */
    p->next = n;
}

void deleteKey(int x) {
    struct node *p, *prev;
    if (head == NULL) { printf("UNDERFLOW\n"); return; }
    if (head->data == x) { p = head; head = head->next; free(p); return; }
    prev = head;
    p = head->next;
    while (p != NULL && p->data != x) { prev = p; p = p->next; }
    if (p == NULL) { printf("%d not found\n", x); return; }
    prev->next = p->next;    /* bypass p */
    free(p);
}

void search(int x) {
    struct node *p = head;
    int pos = 1;
    while (p != NULL) {
        if (p->data == x) { printf("found at position %d\n", pos); return; }
        p = p->next;
        pos++;
    }
    printf("%d not found\n", x);
}

void reverse(void) {
    struct node *prev = NULL, *p = head, *nxt;
    while (p != NULL) {
        nxt = p->next;       /* remember the rest of the list */
        p->next = prev;      /* flip the link                 */
        prev = p;
        p = nxt;
    }
    head = prev;
}

void traverse(void) {
    struct node *p = head;
    int count = 0, max;
    if (head == NULL) { printf("empty list\n"); return; }
    max = head->data;
    while (p != NULL) {
        count++;
        if (p->data > max) max = p->data;
        p = p->next;
    }
    printf("count = %d, largest = %d\n", count, max);
}

void display(void) {
    struct node *p;
    printf("LIST:");
    for (p = head; p != NULL; p = p->next) printf(" %d", p->data);
    printf("\n");
}

int main(void) {
    char cmd[8];
    int a, b;
    while (scanf("%7s", cmd) == 1) {
        if (cmd[0] == 'I' && cmd[1] == 'F' && scanf("%d", &a) == 1) insertFront(a);
        else if (cmd[0] == 'I' && cmd[1] == 'E' && scanf("%d", &a) == 1) insertEnd(a);
        else if (cmd[0] == 'I' && cmd[1] == 'A' && scanf("%d %d", &a, &b) == 2) insertAfter(a, b);
        else if (cmd[0] == 'D' && scanf("%d", &a) == 1) deleteKey(a);
        else if (cmd[0] == 'S' && scanf("%d", &a) == 1) search(a);
        else if (cmd[0] == 'R') reverse();
        else if (cmd[0] == 'T') traverse();
        else { printf("BAD COMMAND\n"); break; }
        display();
    }
    while (head != NULL) { struct node *t = head; head = head->next; free(t); }
    return 0;
}
Sample run · count and largest (Nov 2025 Q4) · real output from gcc

Input (stdin)

IE 12
IE 45
IE 7
IE 30
T
D 7
R

Output (stdout)

LIST: 12
LIST: 12 45
LIST: 12 45 7
LIST: 12 45 7 30
count = 4, largest = 45
LIST: 12 45 7 30
LIST: 12 45 30
LIST: 30 45 12

Open in the Code Lab →

Complexity

OperationTime
Insert at front / delete frontO(1)
Insert at end (no tail pointer)O(n)
Insert at end (with tail pointer)O(1)
Search, count, largest, appendO(n)
Insert after a known nodeO(1)

Array vs linked list (model paper Q5)

ArrayLinked list
Memorycontiguous, fixed size; may waste or run outscattered, grows as needed; extra pointer per node
Access k-th elementO(1)O(k)
Insert/delete at frontO(n) (shift)O(1)
Insert/delete in the middleO(n) (shift)O(1) once the position is known
Cache performancegoodpoor

Edge cases

  • Empty list (head = NULL) in every operation.
  • Deleting the head node — head itself must change.
  • Single-node list: insert at end and delete must still work.
  • malloc returning NULL.

Common mistakes

  • head = new before new→link = head (the list is lost).
  • Forgetting free() after deleting (memory leak).
  • Traversing with head itself instead of a temporary pointer p.
  • Looping while p→link ≠ NULL when you need to visit the last node too.

Asked in KTU exams (9)

Quick check — can you get them all?

Question 1

Q1.struct node { int data; struct node *link; }; This is a…

Question 2

Q2.Insert at the beginning: which order is correct?

Question 3

Q3.Accessing the k-th element of a linked list costs…

Practice

Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.

Exam-ready summary

  • Node = data + link; self-referential struct.
  • Front insert: new→link = head; head = new. O(1).
  • End insert: walk to the last node; last→link = new. O(n).
  • Delete: keep prev; prev→link = p→link; free(p).
  • Arrays: fast access. Lists: fast insert/delete and flexible size.

References

  • Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 4 (§4.1–4.2)
  • Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3/e — §10.2

Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.

Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)