Friday, 5 July 2013

THIS PROGRAM DELETES A NODE FROM GIVEN LOCATION OF DOUBLY LINKED LIST



#include<stdio.h>
#include<malloc.h>

struct dlist
{
    int info;
    struct dlist *link;
    struct dlist *prev;
};

int i ;
struct dlist start;

void del_node (struct dlist *);
void create_dlist (struct dlist *);
void display (struct dlist *);

/* Function to  create doubly linked list */

void create_dlist(struct dlist *ptr)
{
    int n;
    start.link = NULL;  /* Empty list */
    start.prev = NULL;
    ptr = &start;      /* Ptr points to the start pointer */
    printf("\n How many nodes you want to create: ");
    scanf("%d",&n);
    printf("\n\n ==============================================================================\n");
    printf("\n Note That:\n -----------\n Enter numeric data in node\n");
    printf("\n ==============================================================================\n");
    while( i!=n)
    {
        ptr->link = (struct dlist *) malloc(sizeof(struct dlist));
        ptr->link->prev = ptr;
        ptr = ptr->link;
        printf("\n Enter the values of the node : %d: ", (i+1));
        scanf("%d", &ptr->info);
        ptr->link = NULL;
        i++;
    }
    printf("\n\n --------------------");
    printf("\n Total nodes = %d",i);
    printf("\n --------------------\n\n");
}

/* Function to delete a node  */

void del_node (struct dlist *ptr)
{
    int loc;
    int count = 0;
    printf("\n\n\n ---------------------------------------");
    printf("\n Enter the location you want to delete: ");
    scanf("%d", &loc);

    ptr = start.link;
    if ( ptr == NULL)
    {       printf("\n\n======================");
        printf("\n Underflow\n");
        printf("\n List is empty\n");
        printf("====================\n");
    }
    else

        while(ptr)
        {
            if((count + 1) == loc)
            {
                ptr->prev->link = ptr->link ;
                ptr->link->prev = ptr->prev ;
                free(ptr);
            }
            else
            {
                ptr = ptr->link;

            }
            count++;
        }

}

/* Function to display the list */

void display(struct dlist *ptr)
{
    ptr = start.link;

    while (ptr)
    {

        printf("\n\n\t\t%d", ptr->info);
        ptr = ptr->link;
    }
}

/* Main Function */

void main()
{
    struct dlist *ptr = (struct dlist *) malloc(sizeof(struct dlist));
    clrscr();
    create_dlist(ptr);
    printf("\n\n ----------------------");
    printf("\n Doubly linked list is: ");
    printf("\n ----------------------");
    display(ptr);
    del_node(ptr);
    printf("\n\n\n ----------------------------------");
    printf("\n Doubly linked list after deletion: ");
    printf("\n ----------------------------------");
    display(ptr);
    getch();
}

No comments:

Post a Comment