C Program to insert an element at any position in Singly Linked List | C Program

C Program to insert an element at any position in Singly Linked List
SINGLY LINKED LIST

  Singly Linked List | C Program

#include<stdio.h>

#include<stdlib.h>

struct node
{
    int data;
    struct node *next;
};
struct node *start=NULL;

main()
{
    int i,value,ne,pos,invalid;  // ne=Number of element in list, pos= position

    struct node *n,*temp;

    n=malloc(sizeof(struct node));


    printf("\n\n\tHow many value do you want to Enter in List: ");
    scanf("%d",&ne);

    printf("\nEnter first data for list: ");
    scanf("%d",&value);

    n->data=value;
    n->next=NULL;
    start=n;

    for(i=2;i<=ne;i++)
    {
        n=malloc(sizeof(struct node));

        printf("Enter next data: ");
        scanf("%d",&value);

        n->data=value;
        n->next=NULL;
        temp=start;

        while(temp->next!=NULL)
            temp=temp->next;

        temp->next=n;
    }

    if(start==NULL)
        printf("\n\t** List is empty **");

    else
    {
        temp=start;

        printf("\n\tData in the List: ");

        while(temp!=NULL)
        {
            printf("%d\t",temp->data);

            temp=temp->next;
        }
    }

    // for insertion at any position
    printf("\n\nIn which Position do you want to Insert: ");
    scanf("%d",&pos);

    printf("\nWhat value do you want to insert at %d Position: ",pos);
    scanf("%d",&value);

    n=malloc(sizeof(struct node));

    n->data=value;
    n->next=NULL;
    temp=start;

    if(pos==1)
    {
       n->next=start;
       start=n;
    }

    else
    {
        for(i=1;i<pos-1;i++)
        {
            if(start==NULL)
                printf("List is empty");

            else
                temp=temp->next;

            if(temp==NULL)
                break;
        }

        if(temp==NULL)
        {
            invalid=1;
            printf("\n\t\t*** Invalid Position ***");
        }

        else
        {
            n->next=temp->next;
            temp->next=n;
        }
    }

    if(start==NULL)         // for display
        printf("\n\t** List is empty **");

    else
    {
        if(invalid==1)
            printf("\n\t* Could not insert Data due to invalid position *");

        else
            printf("\n\n\t***** Data Inserted Successfully *****");

        temp=start;
        printf("\n\n\tUpdated List:");
        while(temp!=NULL)
        {
            printf("\t%d",temp->data);
            temp=temp->next;
        }
    }
    getch();
}

OUTPUT:                  ->At any position

 

                                 For invalid position

Post a Comment

0 Comments