Lesson 4 of 14
Push Front
Inserting at the Front
Adding a node to the front of a list is O(1) — the cheapest insertion in a linked list.
Create the new node, point its next to the current head, and return it as the new head:
struct Node *push_front(struct Node *head, int val) {
struct Node *n = new_node(val);
n->next = head;
return n;
}
Before: [2] -> [3] -> NULL
After: [1] -> [2] -> [3] -> NULL (push_front(head, 1))
Why Return the New Head?
In C, if we just modify n->next, the caller's head variable still points to the old first node. We must return the new node and let the caller update their pointer:
head = push_front(head, 10);
Push Order
Calling push_front repeatedly builds the list in reverse order:
head = push_front(NULL, 1); // [1]
head = push_front(head, 2); // [2] -> [1]
head = push_front(head, 3); // [3] -> [2] -> [1]
Your Task
Implement struct Node *push_front(struct Node *head, int val) that prepends a node and returns the new head.
TCC compiler loading...
Loading...
Click "Run" to execute your code.