Subscribe Us

Responsive Advertisement

Advertisement

Insert a node in link list at beginning in c data structure

 Insert a node in link list at beginning in c data structure




#include<stdio.h>

#include<stdlib.h>

struct node

{

    int data;

    struct node *next;


};

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

{

    struct node *temp=NULL,*head=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 insertatbegin(struct node *head2,int value)

{

    struct node *temp=NULL;

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

    temp->data=value;

    temp->next=head2;

    while(temp!=NULL)

    {

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

        temp=temp->next;

    }

}

int main()

{

    int n;

    printf("Enter array size : ");

    scanf("%d",&n);

    int arr[n];

    printf("Enter array element : ");

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

    scanf("%d",&arr[i]);

    struct node *head,*head1;

   head= create_link_list(arr,n);

   head1=head;

   while(head1!=NULL)

   {

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

       head1=head1->next;

   }

   printf("\n");

   insertatbegin(head,200);


}


Post a Comment

0 Comments