C in 100 Seconds: Linked List Insert and Delete
Video: C in 100 Seconds: Linked List — Insert and Delete | Episode 43 by Taught by Celeste AI - AI Coding Coach
Watch full page →Linked List — Insert and Delete
Three core operations on a linked list: insert at the head, insert at the tail, and delete by value. Each one is about rewiring pointers.
Insert at Head
Node *insert_head(Node *head, int value) {
Node *n = create_node(value);
n->next = head;
return n;
}
Create a new node, point its next to the current head, and return the new node. The caller updates head: head = insert_head(head, 5);
Insert at Tail
void insert_tail(Node *head, int value) {
Node *n = create_node(value);
Node *c = head;
while (c->next != NULL) {
c = c->next;
}
c->next = n;
}
Walk to the last node (where next is NULL), then link the new node there.
Delete by Value
Node *delete_node(Node *head, int value) {
if (head->data == value) {
Node *next = head->next;
free(head);
return next;
}
Node *c = head;
while (c->next != NULL && c->next->data != value) {
c = c->next;
}
if (c->next != NULL) {
Node *temp = c->next;
c->next = temp->next;
free(temp);
}
return head;
}
Two cases: if the target is the head, free it and return the next node. Otherwise, find the node before the target, rewire around it, and free.
Student Code
Try it yourself: episode43/listops.c