Simvik

Reverse a linked list

Reverse a singly linked list in place. A medium embedded C problem (Buffers and data structures), run and graded in the browser.

medium · Buffers and data structures · linked-list

Reverse the list that starts at head by re-pointing the next links, without allocating or copying nodes. Return the new head. An empty list is NULL.

Starter code

node_t *list_reverse(node_t *head) {
  // Re-point every next link; return the old tail, which is the new head.
  return head;
}

Example tests

Three nodes

node_t c = { 3, NULL }, b = { 2, &c }, a = { 1, &b };
print_list(list_reverse(&a));

Expected output:

3 2 1

Empty list

printf("%s\n", list_reverse(NULL) == NULL ? "null" : "not null");

Expected output:

null

Learn it first

More Buffers and data structures problems