What is the idiomatic way of writing prepend for a linked list?

I started writing a linked list implementation in C:

typedef struct node node;
struct node {
    node *next;
    int value;
};

I can easily write an append function that attaches a new node to the end of the list:

void append(node *head, int value) {
    if (! head->next) {
        head->next = malloc(sizeof(node));
        head->next->value = value;
        return;
    }

    append(head->next, value);
}

If I wrote preend using a functional language such as Scheme, then it would be obvious to just return a new node with "next", pointing to the previous chapter:

(define (prepend head value)
        (cons value head))

and I can easily write this in C:

node *prepend(node *old_head, int value) {
    node* head = malloc(sizeof(node));
    head->value = value;
    head->next = old_head;

    return head;
}

but now my function appendreturns nothing and just changes the list, while my function prependreturns something and does not change the original list. This is a side effect of implementing linked lists, but it does not feel right.

prepend, node, node ...

void prepend(node *head, int value) {
    node* new = malloc(sizeof(node));
    memcpy(new, head, sizeof(node));

    head->next = new;
    head->value = value;
}

- .

head node, , node:

typedef struct list list;
struct list {
    node *head;
};

prepend , list->head , . , ; ( -).

C?


. C , .

+4
1

, "" , struct list. . , , - , .

+2

All Articles