Top Banner Ad

ACS201 — Unit 2: Linked List

Table of Contents (15 sections)

ACS201 · Essentials of Data Structures · Unit 2

Linked List

Unit Scope & Exam Weightage: This unit replaces fixed-size arrays with pointer-connected nodes: Node — data + pointer, why linked list over array, Singly linked list — insert (head, tail, position), delete, traverse, and the concept-only forms Doubly linked list and Circular linked list. The solutions file supplies only generic model-paper templates, so all solved questions are labelled predicted and follow the exact syllabus topics and assignment traces.


Front Page: Importance-Wise Topic Roadmap (Predicted from Syllabus)

Priority Topic (Exact Syllabus) PYQs Asked Marks Weightage Tag
1 Singly linked list — insert (head, tail, position) / delete / traverse 0 real PYQs predicted 7m Predicted Program
2 why linked list over array 0 real PYQs predicted 7m + 2m Predicted Comparison
3 Node — data + pointer 0 real PYQs predicted 2m Predicted Theory
4 Doubly linked list — concept and structure only 0 real PYQs predicted 5m Predicted Concept
5 Circular linked list — concept only Real connect: Browser back/forward = doubly linked list 0 real PYQs predicted 2m Predicted Concept
6 Music playlist = circular integrated in #5 — Real Connect
7 Python deque = doubly linked list (used in BFS, LRU cache) integrated in #4 — Real Connect
8 Linked List (unit title/topic) integrated throughout — Unit Frame

2-Hour Last-Night Survival Checklist:

  1. Insert at head: new->next = head; head = new;. Always link the new node to the old head before moving head, or the rest of the list is lost.
  2. Insert at tail: traverse with p = head; while(p->next != NULL) p = p->next;, then p->next = new; new->next = NULL;.
  3. Delete by value: keep prev one node behind; if the target is head, move head = head->next; otherwise prev->next = target->next, then free(target).
  4. Cost table: array access O(1) but middle insert/delete O(n); linked list access O(n) but insert/delete at a known node O(1). This comparison is a guaranteed 7-mark question.
  5. Doubly vs circular: doubly node has prev and next (browser back/forward); circular makes the last node point to the head (music playlist loop).

1. Node — Data + Pointer

Node: the basic unit of a linked list containing two fields—data (the value stored) and pointer (the address of the next node). The last node's pointer is NULL, marking the end of the list.

struct node {
    int data;
    struct node *next;
};
head ──▶ [10 | •] ──▶ [20 | •] ──▶ [30 | NULL]
Field C declaration Purpose
data int data; Stores the element value
next struct node *next; Stores address of successor
head struct node *head; External pointer to first node

Memory picture: nodes need not be adjacent. Each malloc(sizeof(struct node)) can return any free block; the next pointer supplies the logical order. This is why insertion does not require shifting elements.

Examiner Tip: A 2-mark “node” answer earns full credit with a labelled box diagram data | next and one sentence saying the last next is NULL. Do not confuse next (pointer field) with the head pointer variable.


2. Why Linked List Over Array

Criterion Array Singly linked list
Memory Contiguous, fixed size Non-contiguous, allocated at run time
Access by index O(1) via base address O(n) must follow pointers
Insert at head O(n) shift, or impossible if full O(1) with head pointer
Insert at tail O(1) if capacity and n known O(n) traversal to last node
Delete middle O(n) shifting O(1) once predecessor is known
Memory overhead none one pointer per node
Suitable for read-heavy, fixed-size data frequent insertions/deletions

Decision rule: choose an array when the size is known and random access dominates; choose a linked list when the size changes frequently and insertions/deletions dominate. A music playlist that constantly adds/removes songs is naturally a list; a lookup table indexed by roll number is naturally an array.

%%{init: {'theme': 'base', 'look': 'handDrawn', 'themeVariables': {'fontFamily': "'Nunito', sans-serif", 'fontSize': '17px', 'primaryColor': '#EFEAD6', 'primaryBorderColor': '#0F766E', 'lineColor': '#23211C'}}}%%
flowchart TD
    A[Need a linear collection] --> B{Size fixed and random access?}
    B -->|yes| C[Array: O(1) index]
    B -->|no| D{Frequent insert/delete?}
    D -->|yes| E[Linked list: O(1) at known node]
    D -->|no| F[Either; prefer array for simplicity]

3. Singly Linked List Operations

3.1 Insert at head, tail and position

#include <stdio.h>
#include <stdlib.h>

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

void insertHead(int x) {
    struct node *p = malloc(sizeof(struct node));
    p->data = x;
    p->next = head;      /* link to old first node */
    head = p;            /* new node becomes first */
}

void insertTail(int x) {
    struct node *p = malloc(sizeof(struct node)), *q;
    p->data = x; p->next = NULL;
    if (head == NULL) { head = p; return; }
    for (q = head; q->next != NULL; q = q->next);
    q->next = p;
}

void insertAt(int pos, int x) {          /* pos is 0-based */
    struct node *p, *q = head;
    if (pos == 0) { insertHead(x); return; }
    for (int i = 0; i < pos-1 && q != NULL; i++) q = q->next;
    if (q == NULL) return;               /* position out of range */
    p = malloc(sizeof(struct node));
    p->data = x; p->next = q->next; q->next = p;
}

3.2 Delete and traverse

void deleteValue(int key) {
    struct node *p = head, *prev = NULL;
    while (p != NULL && p->data != key) { prev = p; p = p->next; }
    if (p == NULL) return;                       /* not found */
    if (prev == NULL) head = p->next;            /* deleting head */
    else prev->next = p->next;                   /* bypass target */
    free(p);
}

void traverse(void) {
    for (struct node *p = head; p != NULL; p = p->next)
        printf("%d -> ", p->data);
    printf("NULL\n");
}
Operation Steps Complexity
Insert head allocate, next=head, head=p O(1)
Insert tail traverse to end, link O(n)
Insert at position k traverse k-1 hops, link O(k) ≤ O(n)
Delete head head = head->next, free O(1)
Delete by value search with prev, bypass O(n)
Traverse follow next until NULL O(n)

Assignment trace: inserting 10, 20, 30 at head yields 30 → 20 → 10 → NULL because each new node becomes the first. Deleting node 20 from 10 → 20 → 30 → NULL gives 10 → 30 → NULL.


4. Doubly and Circular Linked Lists (Concept Level)

Doubly linked list: each node has prev and next pointers, allowing traversal in both directions. Circular linked list: the last node's next points back to the head instead of NULL, forming a loop.

struct dnode {
    int data;
    struct dnode *prev;
    struct dnode *next;
};
Doubly:   NULL ← [10] ⇄ [20] ⇄ [30] → NULL
Circular: head → [10] → [20] → [30] ─┐
               ^______________________|
Feature Singly Doubly Circular
Pointers per node 1 (next) 2 (prev, next) 1 or 2
Backward traversal No Yes Only with prev
End marker NULL NULL both ends back to head
Real connect simple queue Browser back/forward, deque, LRU cache Music playlist loop

Python deque: collections.deque is implemented as a doubly linked list, giving O(1) appendleft() and popleft(). It is used in BFS and LRU-cache implementations, linking this concept to Unit 5 graph traversal.

Examiner Tip: For “concept and structure only”, draw the node with both pointers, write the struct definition, and name one real use. Do not attempt a full doubly-linked deletion algorithm—the syllabus explicitly limits depth.


5. Real Connect Summary

Syllabus phrase Meaning in code
Browser back/forward = doubly linked list prev moves back in history, next moves forward
Music playlist = circular After the last song, playback returns to the first
Python deque = doubly linked list (used in BFS, LRU cache) appendleft/popleft are O(1) because both ends are directly reachable

6. Predicted Exam-Ready Questions (Solved — Not Verbatim PYQs)

Predicted Q1 (2 Marks | Node)

Q (predicted from “Node — data + pointer”): Draw and describe a node of a singly linked list.

Solution: A node is data | next. The data field stores the element; the next field stores the address of the following node. The final node has next = NULL. In C: struct node { int data; struct node *next; };.


Predicted Q2 (7 Marks | Why linked list over array)

Q (predicted from “why linked list over array”): Compare linked list and array on memory, access, insertion and deletion. State when each is preferred.

Solution: Use the Section 2 table. Conclusion: arrays give O(1) indexed access and no pointer overhead but fixed size and O(n) shifting; linked lists grow dynamically and insert/delete at a known node in O(1) but need O(n) traversal to find a position and one pointer of extra memory per node. Prefer array for roll-number lookup; prefer linked list for a changing playlist.


Predicted Q3 (7 Marks | Insert head/tail/position)

Q (predicted from assignment “Draw linked list after inserting 10, 20, 30 at head” and “insert node at tail”): Starting from an empty list, insert 10, 20, 30 at the head, then insert 40 at the tail. Show each intermediate list.

Solution:

  1. Insert 10 at head: 10 → NULL.
  2. Insert 20 at head: 20 → 10 → NULL.
  3. Insert 30 at head: 30 → 20 → 10 → NULL.
  4. Insert 40 at tail: traverse 30 → 20 → 10, set last next to 40: 30 → 20 → 10 → 40 → NULL.

Head insertion is O(1); tail insertion is O(n) without a tail pointer.


Predicted Q4 (7 Marks | Delete by value)

Q (predicted from assignment “Trace deletion of node 20 from [10→20→30→NULL]”): Delete node 20 from 10 → 20 → 30 → NULL using a predecessor pointer. Show pointer updates.

Solution:

  1. Start p = head (10), prev = NULL.
  2. p->data != 20 → prev = p (10), p = p->next (20).
  3. For node 20, prev is node 10. Set prev->next = p->next, so node 10 now points to node 30.
  4. free(p) releases node 20.
  5. Result: 10 → 30 → NULL. If the value to delete were the head, the update would be head = head->next.

Predicted Q5 (7 Marks | Doubly/Circular concept)

Q (predicted from “Doubly linked list — concept and structure only” and “Circular linked list — concept only”): Draw the structure of a doubly linked node and explain two real applications of doubly and circular lists.

Solution: Doubly node: prev | data | next with the C struct from Section 4. Applications: browser history uses prev/next to move back and forward; deque uses both ends for BFS and LRU caches. Circular list: last node links to head; a music playlist loops back to the first song, and a round-robin scheduler cycles through tasks.


7. Practice Questions (Self-Test)

  1. (2 Marks) What is stored in the next field of the last node of a singly linked list? (Ans: NULL.)
  2. (7 Marks) Write a C function int count(struct node *head) that returns the number of nodes. (Hint: traverse with a counter.)
  3. (7 Marks) Insert 5 at position 2 (0-based) in 10 → 20 → 30 → NULL and show pointer assignments.
  4. (5 Marks) State two advantages and one disadvantage of a doubly linked list over a singly linked list.
  5. (7 Marks) Explain how a circular list avoids a special case when the last node's next is examined in a playlist loop.