Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
541 B
1
Indexable
Never
struct node *insert_second_last(int value, struct node *head) {

    struct node *new_node = malloc(sizeof(struct node));

    new_node->data = value;
    new_node->next = NULL;

    int list_length = get_list_length(head);

    if (head == NULL || list_length == 1) {
        new_node->next = head;
        return new_node;
    }

    struct node *p = head;
    int i = 1;
    while (p->next != NULL && i + 1 < list_length) {
        p = p->next;
        i++;
    }

    new_node->next = p->next;
    p->next = new_node;

    return head;
}
Leave a Comment