C program for basic linked list implementation with Create, Display, count (number of nodes), insert functions
#include<stdio.h>
#include<stdlib.h>
typedef struct Node // Node structure
{
int data;
struct Node *next;
}Node;
Node *first=NULL;
void create(int A[],int n) // function to create a structure
{
first=(Node *)malloc(sizeof(Node));
first->data=A[0];
first->next=NULL;
Node *temp;
temp=(Node*)malloc(sizeof(Node*));
first->next=temp;
temp->next=NULL;
for(int i=1;i<=n;i++)
{
temp->next=(Node *)malloc(sizeof(Node));
temp->data=A[i];
if(i==n)
{temp->next=NULL;
break;
}
else
temp=temp->next;
}
}
int count(Node *p) // to count the number of nodes in the list
{
int count=0;
while(p->next!=NULL)
{
count=count+1;
p=p->next;
}
return count;
}
void Display(Node *p) // function to display the list
{
while(p->next!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
void insert(int index, int key) // function to insert the elements in the list
{
if(index<0 || index>count(first)) // to check the index
{
printf("\nErr... Invalid index");
}
if(index==0) // if index is the first node then it the new node should be
// the first node
{
Node *temp=(Node *)malloc(sizeof(Node));
temp->data=key;
temp->next=first;
first=temp;
}
if(index==count(first)) // if new node is the last node to be inserted
{ Node *temp=first;
int i=1;
//while(temp->next!=NULL)
while(i<index)
{
temp=temp->next;
i++;
}
Node *last=(Node *)malloc(sizeof(Node));
if(temp->next ==NULL)
printf("\n we are the last node");
temp->next=last;
last->data=key;
//last->data=key;
last->next=NULL;
}
if(index!=0 && index !=count(first)) // if the new node is not the first or the last
{
Node *temp=first;
int count=1;
while(count<index)
{
temp=temp->next;
count++;
}
Node *last=(Node *)malloc(sizeof(Node));
last->data=key;
last->next=temp->next;
temp->next=last;
}
}
int main()
{
int A[]={1,3,5,12};
create(A,(sizeof(A)/sizeof(A[0])));
insert(4,10);
Display(first);
return(0);
}
I/p: insert(0,10) o/p: 10 1 3 5 12
I/p: insert(1,10) o/p: 1 10 3 5 12
I/p: insert(2,10) o/p: 1 3 10 5 12
I/p: insert(3,10) o/p: 1 3 5 10 12
I/p: insert(4,10) o/p: 1 3 5 12 -----> This is the one that I'm getting stuck at I'm supposed to get 1 3 5 12 10 as the output