Lesson 8 +35 XP

Singly Linked List - Insertion, Deletion & Reversal

Singly Linked List - Insertion, Deletion & Reversal

The power of a linked list is that inserting or deleting a node only changes a couple of pointers - nothing is shifted. This lesson works through every insertion and deletion case one at a time: what the idea is, the algorithm, a picture of the pointers before and after, and the C code.

Linked list insertion and deletionLinked list insertion and deletion

Notation (as in Lipschutz): INFO[P] and LINK[P] are the data and next-pointer of node P; START points to the first node; AVAIL is the list of free nodes. In C these are p->data, p->next, start and malloc().

1. Getting a New Node

Every insertion begins the same way: take a free node and put the ITEM into it.

PSEUDO
Algorithm GETNODE(ITEM, NEW)
if AVAIL = NULL then
    Write "OVERFLOW" and Exit       // no free node left
NEW ← AVAIL                         // take the first free node
AVAIL ← LINK[AVAIL]                 // AVAIL moves to the next free node
INFO[NEW] ← ITEM

In C this is simply NEW = malloc(sizeof(struct Node)), which returns NULL when memory runs out.

2. Insertion at the Beginning

Idea: the new node points to the old first node, and START now points to the new node.

Algorithm INSFIRST(INFO, LINK, START, AVAIL, ITEM)
GETNODE(ITEM, NEW)                  // step 1: new node holding ITEM
LINK[NEW] ← START                   // step 2: new node points to old first node
START ← NEW                         // step 3: new node becomes the first node
Exit
DIAGRAM
 Before:  START --> [10] --> [20] --> [30] --> NULL

 Step 2:            [5] --+
                          v
          START --> [10] --> [20] --> [30] --> NULL

 Step 3:  START --> [5] --> [10] --> [20] --> [30] --> NULL

How it works

  • The order of steps 2 and 3 matters: if START changed first, the address of the old first node would be lost.
  • It also works for an empty list: LINK[NEW] becomes NULL, and NEW becomes the only node.

Complexity: O(1) - no traversal.

3. Insertion at the End

Idea: walk to the last node (the one whose LINK is NULL) and make it point to the new node.

Algorithm INSEND(INFO, LINK, START, AVAIL, ITEM)
GETNODE(ITEM, NEW)
LINK[NEW] ← NULL                    // new node will be the last node
if START = NULL then                // empty list: new node is the only node
    START ← NEW
    Exit
PTR ← START
while LINK[PTR] ≠ NULL do           // stop at the last node
    PTR ← LINK[PTR]
LINK[PTR] ← NEW                     // old last node points to new node
Exit
DIAGRAM
 Before:  START --> [10] --> [20] --> [30] --> NULL
                                       ^ PTR stops here (LINK = NULL)

 After:   START --> [10] --> [20] --> [30] --> [40] --> NULL

Complexity: O(n) because of the walk. If the program also keeps a TAIL pointer to the last node, the walk disappears and insertion at the end becomes O(1).

4. Insertion After a Given Node (LOC)

Idea: LOC is the address of a node already in the list. The new node takes over LOC's link, then LOC points to the new node.

Algorithm INSLOC(INFO, LINK, START, AVAIL, LOC, ITEM)
// Inserts ITEM after node LOC, or at the front if LOC = NULL
GETNODE(ITEM, NEW)
if LOC = NULL then
    LINK[NEW] ← START               // insert as the first node
    START ← NEW
else
    LINK[NEW] ← LINK[LOC]           // new node points to LOC's successor
    LINK[LOC] ← NEW                 // LOC now points to the new node
Exit
DIAGRAM
 Insert 25 after LOC (the node holding 20)

 Before:  [10] --> [20] --> [30] --> NULL
                   LOC

 Step 1:  [10] --> [20]     [30] --> NULL
                             ^
                    [25] ----+          LINK[NEW] ← LINK[LOC]

 Step 2:  [10] --> [20] --> [25] --> [30] --> NULL
                                        LINK[LOC] ← NEW

Why this order? If we did LINK[LOC] ← NEW first, the address of node 30 would be lost and the rest of the list would be cut off.

Complexity: O(1) once LOC is known.

5. Insertion Into a Sorted List

Idea: find LOC, the last node whose value is less than ITEM, then insert after it. Two pointers walk together: SAVE (the previous node) and PTR (the current node).

Algorithm FINDA(INFO, LINK, START, ITEM, LOC)
// LOC = last node with INFO < ITEM (NULL if ITEM goes first)
if START = NULL then
    LOC ← NULL and Exit
if ITEM < INFO[START] then
    LOC ← NULL and Exit
SAVE ← START
PTR ← LINK[START]
while PTR ≠ NULL do
    if ITEM < INFO[PTR] then
        LOC ← SAVE and Exit         // ITEM belongs between SAVE and PTR
    SAVE ← PTR                      // move both pointers one step
    PTR ← LINK[PTR]
LOC ← SAVE                          // ITEM is larger than everything
Exit

Worked example: insert 25 into 10 → 20 → 30 → 40.

StepSAVEPTRTestAction
1102025 &lt; 20? Nomove on
2203025 &lt; 30? YesLOC = 20

Insert after 20: 10 → 20 → 25 → 30 → 40.

Complexity: O(n) for the search, O(1) for the link change.

6. Deletion of the First Node

Idea: move START to the second node, then return the old first node to AVAIL.

Algorithm DELFIRST(INFO, LINK, START, AVAIL)
if START = NULL then
    Write "UNDERFLOW" and Exit      // nothing to delete
PTR ← START                         // remember the node being removed
START ← LINK[START]                 // second node becomes first
LINK[PTR] ← AVAIL                   // return PTR to the free list
AVAIL ← PTR
Exit
DIAGRAM
 Before:  START --> [10] --> [20] --> [30] --> NULL
 After:   START -----------> [20] --> [30] --> NULL      [10] freed

Complexity: O(1).

7. Deletion of the Last Node

Idea: walk with SAVE and PTR until PTR is the last node; SAVE (the second-last node) becomes the new last node.

Algorithm DELLAST(INFO, LINK, START, AVAIL)
if START = NULL then
    Write "UNDERFLOW" and Exit
if LINK[START] = NULL then          // only one node
    PTR ← START
    START ← NULL
else
    SAVE ← START
    PTR ← LINK[START]
    while LINK[PTR] ≠ NULL do       // move until PTR is the last node
        SAVE ← PTR
        PTR ← LINK[PTR]
    LINK[SAVE] ← NULL               // second-last node becomes last
LINK[PTR] ← AVAIL                   // free the old last node
AVAIL ← PTR
Exit

Complexity: O(n) - even with a TAIL pointer, because the second-last node must be found by walking (a doubly linked list fixes this).

8. Deletion of the Node After a Given Node

PSEUDO
Algorithm DELAFTER(INFO, LINK, LOC, AVAIL)
// Deletes the successor of node LOC
TEMP ← LINK[LOC]
if TEMP = NULL then
    Write "No node after LOC" and Exit
LINK[LOC] ← LINK[TEMP]              // bypass TEMP
LINK[TEMP] ← AVAIL                  // free TEMP
AVAIL ← TEMP
Exit
DIAGRAM
 Before:  [10] --> [20] --> [25] --> [30] --> NULL
                   LOC      TEMP
 After:   [10] --> [20] -----------> [30] --> NULL       [25] freed

Complexity: O(1).

9. Deletion of a Node Containing a Given ITEM

Idea: find the node with INFO = ITEM and its predecessor (because the predecessor's link must change). Again SAVE and PTR walk together.

Algorithm DELETE_ITEM(INFO, LINK, START, AVAIL, ITEM)
if START = NULL then
    Write "UNDERFLOW" and Exit
if INFO[START] = ITEM then          // ITEM is in the first node
    PTR ← START
    START ← LINK[START]
else
    SAVE ← START
    PTR ← LINK[START]
    while PTR ≠ NULL and INFO[PTR] ≠ ITEM do
        SAVE ← PTR
        PTR ← LINK[PTR]
    if PTR = NULL then
        Write "ITEM not in list" and Exit
    LINK[SAVE] ← LINK[PTR]          // predecessor bypasses PTR
LINK[PTR] ← AVAIL                   // return PTR to the free list
AVAIL ← PTR
Exit

Worked example: delete 30 from 10 → 20 → 30 → 40.

StepSAVEPTRINFO[PTR] = 30?
11020No - move on
22030Yes - stop

LINK[20] ← LINK[30] (the node 40), and node 30 is freed: 10 → 20 → 40.

Complexity: O(n) for the search, O(1) for the unlinking.

10. Reversing a Singly Linked List

Idea: walk through the list once and turn every arrow around. Three pointers are needed: PREV (already reversed part), CURR (node being processed) and NEXT (saved so the rest of the list is not lost).

Algorithm REVERSE(START)
PREV ← NULL
CURR ← START
while CURR ≠ NULL do
    NEXT ← LINK[CURR]               // save the rest of the list
    LINK[CURR] ← PREV               // turn this node's arrow around
    PREV ← CURR                     // move PREV forward
    CURR ← NEXT                     // move CURR forward
START ← PREV                        // last node is the new first node
Exit
DIAGRAM
 Start:    NULL    [10] -> [20] -> [30] -> NULL
           PREV    CURR

 Pass 1:   NULL <- [10]    [20] -> [30] -> NULL
                   PREV    CURR

 Pass 2:   NULL <- [10] <- [20]    [30] -> NULL
                           PREV    CURR

 Pass 3:   NULL <- [10] <- [20] <- [30]    NULL
                                   PREV    CURR   -> START = PREV

Complexity: O(n) time, O(1) extra space.

11. Summary of Singly Linked List Operations

OperationTimeKey pointer changes
Insert at beginningO(1)LINK[NEW] ← START; START ← NEW
Insert at endO(n), or O(1) with TAILLINK[last] ← NEW
Insert after LOCO(1)LINK[NEW] ← LINK[LOC]; LINK[LOC] ← NEW
Insert into sorted listO(n)find LOC, then insert after LOC
Delete firstO(1)START ← LINK[START]
Delete lastO(n)LINK[second-last] ← NULL
Delete after LOCO(1)LINK[LOC] ← LINK[LINK[LOC]]
Delete given ITEMO(n)LINK[SAVE] ← LINK[PTR]
ReverseO(n)turn every link around

Common mistakes to avoid

  1. Changing START (or LINK[LOC]) before saving the old link - the rest of the list is lost.
  2. Forgetting the empty-list case (START = NULL) and the one-node case.
  3. Not freeing deleted nodes - a memory leak.
  4. Using a node after free() - a dangling pointer.
💡 Tip

Key points to remember - Always link the new node to its successor first, then link the predecessor to the new node. - Insertion or deletion at a known position is O(1); finding the position is O(n). - Deleting needs the predecessor, so walk with two pointers SAVE and PTR. - Overflow: AVAIL = NULL on insert. Underflow: START = NULL on delete. - Reversal uses three pointers PREV, CURR, NEXT, in O(n) time and O(1) space.

🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Write algorithms to insert a node (a) at the beginning, (b) at the end and (c) after a given node of a singly linked list. (10 Marks)
  • Write: GETNODE with the overflow check, INSFIRST, INSEND, INSLOC, a before/after diagram for each, and their complexities.
  • Q2. Write an algorithm to insert an ITEM into a sorted linked list. (5 Marks)
  • Write: FINDA with SAVE and PTR, then INSLOC; trace inserting 25 into 10, 20, 30, 40.
  • Q3. Write an algorithm to delete a node containing a given ITEM from a linked list. (5 Marks)
  • Write: the first-node case, the SAVE/PTR search, the bypass LINK[SAVE] ← LINK[PTR], and returning the node to AVAIL.
  • Q4. Write a C function to reverse a singly linked list. (5 Marks)