Subscribe Us

Responsive Advertisement

Advertisement

Insert a node in a link list at middle using C .data structure

 

Insert a node in a link list at middle using C .data structure



#include<stdio.h>

#include<stdlib.h>

struct node

{

    int data;

    struct node *next;

};

struct node *create_linklist(int arr[],int size)

{

    struct node *head=NULL,*temp=NULL,*current=NULL;

    for(int i=0;i<size;i++)

    {

        temp=(struct node *)malloc(sizeof(struct node));

        temp->data=arr[i];

        temp->next=NULL;

        if(head==NULL)

        {

            head=temp;

            current=temp;

        }

        else

        {

            current->next=temp;

            current=temp;

        }

    }

    return head;

};

void insert(struct node *head,int position ,int value)

{

     int counter =0;


     struct node *temp=head;

     while(temp!=NULL)

     {

         counter++;

        // printf("%d**",counter);

         if(counter==position-1)

         {

             struct node *newnode=(struct node *)malloc(sizeof(struct node));

             newnode->data=value;

             newnode->next=temp->next;

             temp->next=newnode;

             break;

         }

         else

         {

             temp=temp->next;

         }

     }

     while(head!=NULL)

     {

         printf("%d ",head->data);

         head=head->next;

     }

}

int main()

{


    int a[]={10,20,30,40,50,50};

    struct node *head=NULL;

    head=create_linklist(a,6);

    insert(head,3,100);


    return 0;

}


Post a Comment

0 Comments