В Выступление на TED Линус Торвальдс отметил «хороший вкус» примерно на 14:10 в интервью. Я прочитал его примеры «Плохой вкус» и «хороший вкус» и хотел реализовать тот же принцип для функции, которая удаляет последний узел в односвязном списке. Я также следил его стиль кодирования.
#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 failedn");
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 underflown");
exit(EXIT_FAILURE);
}
struct node **cursor = &head;
while ((*cursor)->next != NULL)
cursor = &(*cursor)->next;
free(*cursor);
*cursor = NULL;
}