THIS PROGRAM INSERTS AN ITEM INTO SORTED LINKED LIST



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

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

int i;
int num;
struct list start, *prev, *new1;

void insert_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 in ASCENDING ORDER\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 insert an item */
void insert_node(struct list *ptr)
{

    int item;

    ptr = start.link;
    prev = &start;
    printf("\n\n --------------------------------------");
    printf("\n Enter the item you want to insert:");
    scanf("%d",&item);

    while((item > (ptr->info)) && (ptr!=NULL))
    {
        prev=ptr;
        ptr= ptr->link;
    }

        new1 = (struct list *) malloc(sizeof(struct list));
        new1->link = ptr;
        prev->link = new1;
        new1->info = item;
}

/* Main Function */

void main()
{
    struct  list *ptr = (struct list *) malloc(sizeof(struct list));
    clrscr();
    create_list(ptr);
    printf("\n ----------------------");
    printf("\n Linked list is:\n");
    printf("\n ----------------------");
    display(ptr);
    insert_node(ptr);
    printf("\n\n\n ----------------------------");
    printf("\n Linked list after insertion: \n");
    printf("\n ----------------------------");
    display(ptr);
    getch();
}


Comments

Popular posts from this blog

Write a program to add two number using inline function in C++?

Traversing of elements program with algorithm and Flowchart