In a TED talk Linus Torvalds made a point about “good taste” at approximately 14:10 in the interview. I read through his examples of “bad taste” and “good taste” and wanted to implement the same principle for a function that deletes the last node in a singly linked list. I also followed his coding style.
#include <stdio.h>
#include <stdlib.h>
/* linked list structure */
struct node {
int data;
struct node *next;
};
/* create new node */
struct node *new_node(int data, struct node *next)
{
struct node *new = malloc(sizeof *new);
if (!new) {
fprintf(stderr, "Error: memory allocation failed\n");
exit(EXIT_FAILURE);
}
new->data = data;
new->next = next;
return new;
}
/* delete last node */
void delete_last(struct node *head)
{
if (head == NULL) {
fprintf(stderr, "Error: linked list underflow\n");
exit(EXIT_FAILURE);
}
struct node **cursor = &head;
while ((*cursor)->next != NULL)
cursor = &(*cursor)->next;
free(*cursor);
*cursor = NULL;
}
exit()from a minor function call. \$\endgroup\$voidmake itint(or if you like bools, add thestdboolheader) and return something to indicate the failure to the calling function. \$\endgroup\$new_nodemethod either needs documentation or is anew_element_beforebecause it's not inserting at a random point it's inserting in a way that would break an existing list (if you put it say before the last element) - you'd end up with a final node pointed to by two nodes. \$\endgroup\$