LINKED LIST TO ADD NODE IN GIVEN POISITION
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
void printLL(struct node *ptr){
while(ptr != NULL){
printf("element = %d \n",ptr->data);
ptr=ptr->next;
}
}
struct node* addatindex(struct node* head,int data ,int index){
struct node * ptr = (struct node*) malloc(sizeof(struct node));
struct node* p = head;
int i =0 ;
while(i!=index-1){
p=p->next;
i++;
}
ptr->data=data;
ptr->next=p->next;
p->next=ptr;
return head;
}
int main()
{ struct node* head;
struct node* second;
struct node* third;
head=(struct node*)malloc(sizeof(struct node));
second=(struct node*)malloc(sizeof(struct node));
third=(struct node*)malloc(sizeof(struct node));
head->data=11;
head->next=second;
second->data=55;
second->next=third;
third->data=66;
third->next=NULL;
printf("linked list before insertion\n");
printLL(head);
printf("linked list after insertion \n");
head=addatindex(head,99,2);
printLL(head);
return 0;
}
0 Comments