data-structures · intermediate · ~15 min
Mutating a linked list while preserving its head.
Append a new node to the end of a singly linked list and return the head.
The grader supplies the same node type as the previous exercise:
typedef struct node { int data; struct node *next; } node_t;
Implement node_t *insert(node_t *head, int value) that allocates a new node holding value, appends it at the end of the list, and returns the (possibly new) head. No main — the grader calls it.
head: pointer to the first node, or NULL for an empty list.value: the int to store in the new tail node.The head of the list after appending. If head was NULL, the new node becomes the head and is returned.
insert(NULL, 1) -> list 1
insert(1->2, 3) -> list 1->2->3
head == NULL) returns the new node as the head.malloc.head (or NULL) and the int value for the new tail node.
The head of the list after appending the new node.
Allocate the new node with malloc; an empty list returns the new node.
#include <stdlib.h>
node_t *insert(node_t *head, int value) {
/* TODO */
return head;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.