Sunday, November 8, 2015

Doubly Linked List Implementation in C




# include <stdio.h>
# include <conio.h>


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

void appendNode( struct node **head, int val);
void addAtBegin( struct node **head, int val);
void display_forward_dll( struct node **head);
void display_reverse_dll( struct node **head);


int main(){

struct node *head;

head = NULL;

appendNode( &head, 1);
appendNode( &head, 2);
appendNode( &head, 3);
appendNode( &head, 4);
appendNode( &head, 5);

display_forward_dll(&head);
display_reverse_dll(&head);

addAtBegin( &head, 100);
addAtBegin( &head, 200);
addAtBegin( &head, 300);

display_forward_dll(&head);
display_reverse_dll(&head);

return 0;
}

void appendNode( struct node **head, int val){

    if( *head == NULL){
        struct node *temp = (struct node*)malloc(sizeof(struct node));
        temp->prev = NULL;
        temp->value = val;
        temp->next = NULL;
        *head = temp;
    } else {
        struct node *temp = (struct node*)malloc(sizeof(struct node));
        temp->next = NULL;
        temp->value = val;
        struct node *temp1 = *head;
        while( temp1->next != NULL ){
            temp1 = temp1->next;
        }
        temp1->next = temp;
        temp->prev = temp1;
    }

}

void addAtBegin( struct node **head, int val){

    if( *head == NULL ){
        struct node *temp = (struct node*)malloc(sizeof(struct node));
        temp->prev = NULL;
        temp->value = val;
        temp->next = NULL;
        *head = temp;
    } else {
        struct node *temp1 = *head;
        struct node *temp = (struct node*)malloc(sizeof(struct node));
        temp->prev = NULL;
        temp->value = val;
        temp->next = temp1;
        *head = temp;
    }
}

void display_forward_dll( struct node **head){

    if( *head == NULL){
        printf( "[DOUBLY_LINKED_LIST] is empty\n");
    } else {
        struct node *temp = *head;
        while( temp != NULL){
            printf("[DOUBLY_LINKED_LIST] element in forward is %d \n", temp->value);
            temp = temp->next;
        }
    }
}


void display_reverse_dll( struct node **head){

    if( *head == NULL){
        printf( "[DOUBLY_LINKED_LIST] is empty\n");
    } else {
        struct node *temp = *head;
        while( temp->next != NULL){
            temp = temp->next;
        }
        while( temp->prev != NULL){
            printf("[DOUBLY_LINKED_LIST] element in reverse is %d \n", temp->value);
            temp = temp->prev;
        }

    }
}

No comments:

Post a Comment