data-structures · intermediate · ~15 min

Insert at end

Mutating a linked list while preserving its head.

Challenge

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;

Task

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.

Input

  • head: pointer to the first node, or NULL for an empty list.
  • value: the int to store in the new tail node.

Output

The head of the list after appending. If head was NULL, the new node becomes the head and is returned.

Example

insert(NULL, 1)              ->   list 1
insert(1->2, 3)             ->   list 1->2->3

Edge cases

  • Inserting into an empty list (head == NULL) returns the new node as the head.

Rules

  • Allocate the new node with malloc.

Input format

head (or NULL) and the int value for the new tail node.

Output format

The head of the list after appending the new node.

Constraints

Allocate the new node with malloc; an empty list returns the new node.

Starter code

#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.