Friday, 5 July 2013

THIS PROGRAM DELETES A NODE AT GIVEN LOCATION FROM SIMPLE LINKED LIST



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

struct list
{
    int info;
    struct list *link;
};

int i;
int num ;
struct list start, *prev;
void  del_node(struct list *);
void  create_list(struct list *);
void display(struct list *);

/* Function to create linked list */

 void create_list(struct list *ptr)
 {
    int n;
    ptr = &start;      /* Ptr points to the start pointer */
    printf("\n How many nodes you want to create: ");
    scanf("%d",&n);
    i=0;
    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 list *) malloc(sizeof(struct list));
        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 display the list */

void  display(struct list *ptr)
{
    ptr = start.link;
    while (ptr)
    {
        printf("\n\n\t\t%d", ptr->info);
        ptr = ptr->link;
    }
}
/* Function to delete node from given location */

void del_node(struct list *ptr)
{
    int i= 1;
    int loc;
    ptr = start.link;
    prev = &start;

    printf("\n\n\n Enter the location of node you want to delete:");
    scanf(" %d", &loc);

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

}

/* Main Function */

void main()
{

    struct list *ptr = (struct list *) malloc(sizeof(struct list));
    clrscr();
    create_list(ptr);
    printf("\n Linked list is: ");
    printf("\n ---------------\n");
    display(ptr);
    del_node(ptr);
    printf("\n ---------------------------------------------\n");
    printf("\n Linked list after deletion of last node: \n");
    printf("\n ---------------------------------------------\n");
    display(ptr);
    getch();

}

No comments:

Post a Comment