Friday, 5 July 2013

THIS PROGRAM PERFORMS INSERTION AT THE BEGINNING OF DOUBLY LINKED LIST



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

struct dlist
{
    char info[20];
    struct dlist *link;
    struct dlist *prev;
};

int i;
struct dlist  start, *new1;
void insert_first (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\n\n How many nodes you want to create: ");
    scanf("%d",&n);
    printf("\n\n ==============================================================================\n");
    printf("\n Note That:\n -----------\n Enter string values in nodes\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("%s", ptr->info);
        ptr->link = NULL;
        fflush(stdin);
        i++;
    }
    printf("\n\n --------------------");
    printf("\n Total nodes = %d",i);
    printf("\n --------------------\n\n");
}

/* Fuction to insert node at beginning */

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

    new1 = (struct dlist *) malloc(sizeof(struct dlist ));

    printf("\n\n ---------------------------------------");
    printf("\n Enter the item you want to insert: ");
    gets(new1->info);
    new1->link = ptr;
    new1->prev = ptr->prev;
    ptr->prev->link = new1;
    ptr->prev = new1;

}

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

        while (ptr)
        {

            printf("\n\n\t\t %s", 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 Doudly linked list is:");
    printf("\n ----------------------\n");
    display(ptr);
    insert_first (ptr);
    printf("\n\n\n -------------------------------------------------");
    printf("\n Doudly linked list after insertion at beginning:");
    printf("\n -------------------------------------------------");
    display (ptr);
getch();
}



No comments:

Post a Comment