Doubly LinkedList

Elements are printed both normally and reversely

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

typedef struct node{
    int data;
    struct node *next;
    struct node *prev;
    
}node;

int main(){
    node *head = NULL;
    int num,s;

    printf("enter size of linked list:");
    scanf("%d",&s);
        
    for(int i = 0; i<s; i++){
    
    node *n = (node*)malloc(sizeof(node));
    
    if(n == NULL){
        printf("Memory Allocation Failed\n");
        return 1;
    }
    
    printf("enter value %d : ",i);
    scanf("%d", &num);
    
    n->data = num;
    n->next = NULL;
    n->prev = NULL;
    
    if(head == NULL){
        head = n;
    }
    
    else{
        //variable need to be reach end so that we can add another node
        node *p = head;
        
        while(p->next != NULL){
            p = p->next;
        }
        p->next = n;
        n->prev = p;
    }
    
}
    
    node *ptr = head;
    
    printf("\n\n\t**** Linked List ****\n\n");
    while(ptr != NULL){
        printf("%d->",ptr->data);
        ptr = ptr->next;
    }
    printf("NULL");
    
    node *last = head;
    while( last->next != NULL){
        last = last->next;
    }
    printf("\nReversed Linked list\n");
    while(last != NULL){
        printf("%d<-", last->data);
        last = last->prev;
    }
    printf("null\n");
    //free memory
    ptr = head;
    
    while (ptr != NULL){
        node *temp = ptr;
        ptr = ptr->next;
        free(temp);
    }
}

Comments

Popular posts from this blog

AI and Human Evolution

Snake Game using JAVA

To Do List App (GUI) using C#