Simvik

Sorted insert into a linked list

Insert a caller-provided node into an ascending singly linked list. A medium embedded C problem (Buffers and data structures), run and graded in the browser.

medium · Buffers and data structures · linked-list

Timer lists and ready queues are kept sorted so that the next item to handle is always at the front.

Insert item into the list that starts at head, which is sorted by ascending value, so that it stays sorted. A node with a value equal to existing ones goes after them. Return the head of the updated list. head is NULL for an empty list. No memory is allocated: the caller owns the nodes.

Starter code

node_t *list_insert_sorted(node_t *head, node_t *item) {
  // Link `item` in before the first node with a larger value; return the (possibly new) head.
  return head;
}

Example tests

Build a list from scratch

node_t n[3] = { { 5, NULL }, { 1, NULL }, { 3, NULL } };
node_t *head = NULL;
for (int i = 0; i < 3; i++) head = list_insert_sorted(head, &n[i]);
print_list(head);

Expected output:

1 3 5

Equal values and the tail

node_t n[3] = { { 2, NULL }, { 2, NULL }, { 9, NULL } };
node_t *head = NULL;
for (int i = 0; i < 3; i++) head = list_insert_sorted(head, &n[i]);
print_list(head);

Expected output:

2 2 9

Learn it first

More Buffers and data structures problems