Adding to list
- C course
- Intermediate
- Lesson 71/116
- 5 min
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.
Practice 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.
Starter code
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
// list_push_front: prepend a node, return the new head
// main: prepend 10 then 20 to a NULL head; print head and next data
int main(void) {
// write here
return 0;
}Sample 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;
}Expected output
20 10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The new node's next
n->next = ____;
n->next = head;
Explanation: The new node's next points to the old head.
2 Prepend steps
| Term | Meaning |
|---|---|
step 1 |
allocate with malloc |
step 2 |
set data |
step 3 |
next = head |
step 4 |
return n |
3 What must be done after calling list_push_front?
- set head to NULL
- call free(head)
- delete data
- take head back Correct answer
Explanation: head = list_push_front(head, x) takes the new head back.