#include <stdio.h>
#include <stdlib.h>

struct list_item {
    int value;
    struct list_item *prev, *next;
};

struct doubly_linked_list {
    struct list_item *first, *last;
};

void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void init_list(struct doubly_linked_list *p)
{
    p->first = NULL;
    p->last = NULL;
}

void print_list(const struct doubly_linked_list *p)
{
    struct list_item *tmp;
    for (tmp = p->first; tmp; tmp = tmp->next)
        printf("%d ", tmp->value);
    printf("\n");
}

void insert_right(struct doubly_linked_list *p, struct list_item *curr,
                  int value)
{
    struct list_item *tmp;

    tmp = xmalloc(sizeof(*tmp));
    tmp->value = value;

    tmp->prev = curr;
    if (curr) {
        tmp->next = curr->next;
        curr->next = tmp;
    }
    else {
        tmp->next = p->first;
        p->first = tmp;
    }

    if (tmp->next)
        tmp->next->prev = tmp;
    else
        p->last = tmp;
}

void insert_left(struct doubly_linked_list *p, struct list_item *curr,
                 int value)
{
    struct list_item *tmp;

    tmp = xmalloc(sizeof(*tmp));
    tmp->value = value;

    tmp->next = curr;
    if (curr) {
        tmp->prev = curr->prev;
        curr->prev = tmp;
    } else {
        tmp->prev = p->last;
        p->last = tmp;
    }

    if (tmp->prev)
        tmp->prev->next = tmp;
    else
        p->first = tmp;
}

void remove_item(struct doubly_linked_list *p, struct list_item *curr)
{
    if (curr->prev)
        curr->prev->next = curr->next;
    else
        p->first = curr->next;

    if (curr->next)
        curr->next->prev = curr->prev;
    else
        p->last = curr->prev;
    free(curr);
}

int main()
{
    struct doubly_linked_list l;
    init_list(&l);
    insert_right(&l, l.last, 1);
    insert_right(&l, l.last, 2);
    insert_right(&l, l.last, 3);
    insert_right(&l, l.last, 4);
    remove_item(&l, l.last->prev);

    insert_left(&l, l.first, 5);
    insert_left(&l, l.first, 6);
    insert_left(&l, l.first, 7);
    insert_left(&l, l.first, 8);
    print_list(&l);
    return 0;
}
