C
Adding to list
Learn to add elements to a linked list.
Adding to a list
The easiest way to add a node is to prepend at the head. A new node is allocated, its next points to the old head, and the new node becomes the head.
The function signature is Node *list_push_front(Node *head, int value). Inside: Node *n = malloc(sizeof(Node)); n->data = value; n->next = head; return n;. If head was NULL, the first node is added and n->next becomes NULL. This runs in O(1) time; no need to scan to the end. The caller must take the new head back with head = list_push_front(head, 10);.
Return value and the head
Prepending changes the head. So the function returns the new head and the caller takes it back. This is the C idiom: pass the pointer by value.
The call: head = list_push_front(head, 20);. If you pass head directly and don't take it back, you keep using the old head and the new node is orphaned. Multiple inserts chain: first head = list_push_front(head, 10);, then head = list_push_front(head, 20);. This builds the list 20 -> 10 -> NULL. The most recently added is always at the head.
Exercise Two-node list
Write Node *list_push_front(Node *head, int value): allocate with malloc(sizeof(Node)), set n->data = value;, n->next = head;, return n;. In main start with Node *head = NULL;, prepend 10 then 20. Print with printf("%d %d\n", head->data, head->next->data);. Free both nodes.
Show example solution
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *list_push_front(Node *head, int value) {
Node *n = malloc(sizeof(Node));
n->data = value;
n->next = head;
return n;
}
int main(void) {
Node *head = NULL;
head = list_push_front(head, 10);
head = list_push_front(head, 20);
printf("%d %d\n", head->data, head->next->data);
free(head->next);
free(head);
return 0;
}
Test yourself
-
The new node's next
n->next = ____;
Show answer
n->next = head;
-
Prepend steps
- step 1
- allocate with malloc
- step 2
- set data
- step 3
- next = head
- step 4
- return n
-
What must be done after calling list_push_front?
- set head to NULL
- call free(head)
- delete data
- take head back
Show answer
take head back — head = list_push_front(head, x) takes the new head back.
Next lesson: Traversing list