The big advantage of a linked list is that inserting or deleting a node only changes a few pointers; nothing is shifted. The difficulty is to handle every special case: empty list, first node, last node, key not found. This page gives the algorithms and a tested implementation.
Insertion
Intuition
Adding a coach to a train: uncouple at the right place, couple the new coach to the coach that comes after it, then couple the coach in front to the new one. If you uncouple the front first without holding on to the rest, the back of the train rolls away and is lost.
At the front (O ( 1 ) O(1) O ( 1 ) ): the new node points to the old first node, and head points to the new node.
After a node p (O ( 1 ) O(1) O ( 1 ) once p is known):
n->next = p->next; (new node points to p’s old successor)
p->next = n; (p points to the new node)
The order matters: doing step 2 first would lose the address of the rest of the list.
Before the node holding key : if key is in the first node, insert at the front; otherwise walk with a pointer prev until prev->next holds key, then insert after prev. Finding the place is O ( n ) O(n) O ( n ) .
Deletion
To delete the node holding key:
If the list is empty, there is nothing to delete.
If the first node holds key, set head to the second node and free the first.
Otherwise find prev, the node before the one holding key. If there is none, report “not found”.
Let victim = prev->next; set prev->next = victim->next (bypass it), then free(victim).
A singly linked node has no pointer to its predecessor, so we always search for the node before the one to change.
Example 3.7 Insertions and deletions with every special case
Goal. Build 10 → 30, insert 20 after 10, insert 5 before 10 (new first node), insert 25 before 30, delete the first node, delete a middle node, try to delete a missing key, and finally delete everything.
Program. insert_before and delete_key return the head, because it may change; done reports success.
C · sll_ops.c Copy #include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node * next;
} Node;
Node * new_node( int x, Node * next)
{
Node * n = malloc( sizeof * n);
if (n == NULL ) {
fprintf(stderr, "out of memory \n " );
exit(EXIT_FAILURE);
}
n->data = x;
n->next = next;
return n;
}
void traverse( const Node * head)
{
for ( const Node * p = head; p != NULL ; p = p->next)
printf( "%d -> " , p->data);
printf( "NULL \n " );
}
/* Return the first node holding key, or NULL. */
Node * search(Node * head, int key)
{
Node * p = head;
while (p != NULL && p->data != key)
p = p->next;
return p;
}
/* Insert x at the front; returns the new head. O(1) */
Node * insert_front(Node * head, int x)
{
return new_node(x, head);
}
/* Insert x after the first node holding key. Returns 1 if done. */
int insert_after(Node * head, int key, int x)
{
Node * p = search(head, key);
if (p == NULL )
return 0 ;
p->next = new_node(x, p->next); /* new node points where p pointed */
return 1 ;
}
/* Insert x before the first node holding key; returns the (new) head. */
Node * insert_before(Node * head, int key, int x, int * done)
{
* done = 0 ;
if (head == NULL )
return head;
if (head->data == key) { /* key is the first node */
* done = 1 ;
return new_node(x, head);
}
Node * prev = head; /* find the node BEFORE key */
while (prev->next != NULL && prev->next->data != key)
prev = prev->next;
if (prev->next != NULL ) {
prev->next = new_node(x, prev->next);
* done = 1 ;
}
return head;
}
/* Delete the first node holding key; returns the (new) head. */
Node * delete_key(Node * head, int key, int * done)
{
* done = 0 ;
if (head == NULL ) /* empty list: nothing to delete */
return head;
if (head->data == key) { /* deleting the first node */
Node * rest = head->next;
free(head);
* done = 1 ;
return rest;
}
Node * prev = head;
while (prev->next != NULL && prev->next->data != key)
prev = prev->next;
if (prev->next != NULL ) { /* prev->next is the node to delete */
Node * victim = prev->next;
prev->next = victim->next; /* bypass it ... */
free(victim); /* ... then free it */
* done = 1 ;
}
return head;
}
int main( void )
{
Node * head = NULL ;
int ok;
head = insert_front(head, 30 );
head = insert_front(head, 10 );
traverse(head);
insert_after(head, 10 , 20 ); /* 10 -> 20 -> 30 */
traverse(head);
head = insert_before(head, 10 , 5 , & ok); /* new first node */
traverse(head);
head = insert_before(head, 30 , 25 , & ok); /* in the middle */
traverse(head);
head = delete_key(head, 5 , & ok); /* first node */
traverse(head);
head = delete_key(head, 25 , & ok); /* middle node */
traverse(head);
head = delete_key(head, 99 , & ok); /* not present */
printf( "delete 99: %s \n " , ok ? "deleted" : "key not found" );
while (head != NULL ) /* delete everything */
head = delete_key(head, head->data, & ok);
traverse(head);
return 0 ;
}
Run it.
Output Copy 10 -> 30 -> NULL
10 -> 20 -> 30 -> NULL
5 -> 10 -> 20 -> 30 -> NULL
5 -> 10 -> 20 -> 25 -> 30 -> NULL
10 -> 20 -> 25 -> 30 -> NULL
10 -> 20 -> 30 -> NULL
delete 99: key not found
NULL
Result. Every case gives the expected list, a missing key is reported, and deleting all nodes leaves head == NULL.
Cost of the operations
Operation Singly linked list Array list Insert/delete at the front O ( 1 ) O(1) O ( 1 ) O ( n ) O(n) O ( n ) Insert after a node you already have O ( 1 ) O(1) O ( 1 ) O ( n ) O(n) O ( n ) Insert/delete by key (search first) O ( n ) O(n) O ( n ) O ( n ) O(n) O ( n ) Access the i i i -th element O ( i ) O(i) O ( i ) O ( 1 ) O(1) O ( 1 ) Insert at the end without a tail pointer O ( n ) O(n) O ( n ) O ( 1 ) O(1) O ( 1 )
Correction · Programs 3.5 and 3.6 (insert and delete in a linked list)
Study material says: In Programs 3.5 and 3.6 (§3.4), find ends with else find(start->next, key); without return; Program 3.5 calls mallo; Program 3.6’s main calls insert(head), a function that does not exist (the function is insert_list); both use void main() and the −1111 end node of Program 3.4.
Correct version: The recursive call must be returned: return find(start->next, key);. Better, write find as a loop that stops when prev->next == NULL (see insert_before and delete_key above), which also works for lists with one node. Call malloc and insert_list by their real names, check every malloc, and use int main(void).
Why: A non-void function that ends without return gives an undefined value to its caller (C17 §6.9.1 ¶12); gcc warns “control reaches end of non-void function”. mallo and insert are undeclared, so the programs do not compile. The study-material find also reads start->next->data without checking that start->next exists, which crashes on a one-node list.
Key idea
Insertion and deletion in a linked list change only a few pointers (O ( 1 ) O(1) O ( 1 ) once the position is known), but finding the position, and the node before it, takes O ( n ) O(n) O ( n ) ; the first node and the empty list always need separate handling.
TEE Exam note
For “write an algorithm/function to insert (or delete) a node in a singly linked list”: cover the three cases explicitly (empty list / first node / elsewhere), draw before-and-after diagrams with the changed links numbered in order, write the two pointer assignments in the correct order, and remember free for deletion. State the complexity: O ( 1 ) O(1) O ( 1 ) at the front, O ( n ) O(n) O ( n ) when a search is needed.
Common mistake
Writing p->next = n; n->next = p->next; in that order. After the first line, p->next is n, so n ends up pointing to itself and the rest of the list is lost.
Common mistake
Deleting the first node without updating head. head then points to freed memory, and the next traversal is undefined behaviour.
Common mistake
Freeing the node before linking around it (free(prev->next); prev->next = prev->next->next;). The second line reads freed memory; save the pointer first.
Key takeaways
Insert after p: n->next = p->next; p->next = n; (in this order).
Delete: find the node before the victim, bypass the victim, then free it.
Handle the empty list, the first node and “key not found” separately.
Pointer changes are O ( 1 ) O(1) O ( 1 ) ; searching for the position is O ( n ) O(n) O ( n ) .
Practice questions Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 1 · multiple choice p points to a node in the middle of a list and n is a new node. Which pair of statements inserts n after p correctly?
A p->next = n; n->next = p->next;B n->next = p->next; p->next = n;C n->next = p; p->next = n;D n->next = p->next; p = n;
Check answer
Show answer Answer: B. n->next = p->next; p->next = n;
n must take over p’s old link before p is changed. In the first option n->next becomes n itself, and the rest of the list is lost.
Question 2 · multiple choice What is the time to delete the first node of a singly linked list with n n n nodes?
Check answer
Show answer Answer: A. O ( 1 ) O(1) O ( 1 )
Only head changes; nothing is searched or shifted. Deleting the first element of an array list is O ( n ) O(n) O ( n ) .
Question 3 · multiple choice To delete the node holding key in a singly linked list, which node must the search find?
A The node holding key B The last node C The node just before the one holding key D The node just after the one holding key
Check answer
Show answer Answer: C. The node just before the one holding key
Its next link has to change to bypass the deleted node, and a singly linked node cannot reach its predecessor. (A doubly linked list can.)
Question 4 · multiple choice What does this program print?
C · q3-insert.c Copy #include <stdio.h>
typedef struct node {
int data;
struct node * next;
} Node;
int main( void )
{
Node c = { 3 , NULL }, b = { 2 , & c}, a = { 1 , & b}, n = { 9 , NULL };
Node * p = & b;
n.next = p->next;
p->next = & n;
for (Node * q = & a; q != NULL ; q = q->next)
printf( "%d " , q->data);
printf( " \n " );
return 0 ;
} A 1 9 2 3 B 1 2 3 9 C 9 1 2 3 D 1 2 9 3
Check answer
Show answer Answer: D. 1 2 9 3
p is the node holding 2, so the new node 9 is linked in after it: 1 → 2 → 9 → 3. “1 9 2 3” would be insertion before 2.
Question 5 · multiple choice A function deletes nodes from a list but never updates head when the first node is deleted. What happens on the next traversal after deleting the first node?
A The list is printed without the first node. B The program prints an empty list. C Nothing changes; the node is still in the list. D head points to freed memory, so the behaviour is undefined.
Check answer
Show answer Answer: D. head points to freed memory, so the behaviour is undefined.
The node was freed but head still holds its address (a dangling pointer). It may seem to work, print garbage or crash.
Question 6 · short answer
Write an algorithm to delete the node containing a given key from a singly linked list, covering all cases.
Show worked answer (1) If head == NULL, report “list empty” and stop. (2) If head->data == key: temp = head; head = head->next; free(temp); stop. (3) Set prev = head. While prev->next != NULL and prev->next->data != key, set prev = prev->next. (4) If prev->next == NULL, report “key not found” and stop. (5) Otherwise victim = prev->next; prev->next = victim->next; free(victim);. Time: O ( n ) O(n) O ( n ) for the search, O ( 1 ) O(1) O ( 1 ) for the pointer changes.