C Data Structure: Double Linked List

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

/**
 * Author: Ozan Özenoğlu
 * Date : 10/10/2020
 * */

struct linked_list_node {
    struct linked_list_node *next;
    struct linked_list_node *previous;
    int val;
};
typedef struct linked_list_node linked_list_node_t;


struct linked_list {
    int size;
    linked_list_node_t *head;
    linked_list_node_t *tail;
};

typedef struct linked_list linked_list_t;

void init(linked_list_t *list){
    list->size = 0;
    list->head = (void*)0;
    list->tail = (void*)0;
    printf("double linked list init completed\n");
}


void add(linked_list_t *list , int val) {
    linked_list_node_t *node = malloc(sizeof(linked_list_node_t)*1);
    node->val = val;
    node->next = (void*)0;
    if(list->tail != (void*)0) { // if it is not first node
        node->previous = list->tail;
        list->tail->next = node;
        list->tail = node;

    } else {
        list->tail = node;
    }
    if(list->head == (void*)0) { // if it's first node
        list->head = node;
    }
    list->size++;
}

int get(linked_list_t *list) {
    if(list->size == 0) {
        return -1;
    }
   
    linked_list_node_t *node = list->tail;
    linked_list_node_t *prev = node->previous;
    if(prev != (void*)0) {
        prev->next = (void*)0;
        list->tail = prev;
    } else { // last element in the list
        list->tail = (void*)0;
        list->head = (void*)0;
    }
    int result = node->val;
    free(node);
    list->size --;
    return result;
}

int main() {

    linked_list_t list;
    init(&list);
    add(&list, 1);
    add(&list, 2);
    add(&list, 3);
    add(&list, 4);
    add(&list, 5);

    printf("%d\n",get(&list));
    printf("%d\n",get(&list));
    printf("%d\n",get(&list));
    printf("%d\n",get(&list));
    printf("%d\n",get(&list));
    printf("%d\n",get(&list));
    printf("%d\n",get(&list));
    printf("%d\n",get(&list));

    add(&list, 2);
    add(&list, 3);
    add(&list, 4);
    add(&list, 5);

    printf("%d\n",get(&list));
    printf("%d\n",get(&list));
    printf("%d\n",get(&list));
    printf("%d\n",get(&list));


    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *