I made a program to insert a element in doubly linked list given below(ignore create and display functions Which was working perfectly right till it found the index to be inserted is 5 ,where it fails .Although i made another program to encounter this and now it isn't displaying anything. I used chat gpt but just got wrong answers .Pls help me and also any guidance for when i think a program and its algo it works perfectly but when i actually compile it .It doesn't work, even if i have traced my program like 10 times Another program:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node {
struct Node *prev;
int data;
struct Node *next;
}new;
new *insert (new *head,int index,int num);
void display(new *head);
void create(new *head,int A[],int n);
void create(new *head,int A[],int n)
{
head->data=A[0];
head->next=head->prev=NULL;
new *last=head;
for(int i=1;i<n;i++)
{
new *t=(new *)malloc(sizeof(new));
t->data=A[i];
t->prev=last;
t->next=NULL;
last->next=t;
last=t;
}
}
void display(new *head)
{
new * temp=NULL;
int flag=0;
printf("Next:");
while(head)
{
printf("%d ",head->data);
if(!head->next||flag==0){
temp=head;
flag=1;
}
head=head->next;
}
printf("\nPREV:");
while(temp)
{
printf("%d ",temp->data);
temp=temp->prev;
}
printf("\n");
}
new *insert (new *head,int index,int num)
{
new*q=NULL,*temp=NULL;
int flag=0;
if(index==0)
{
return insert(head,0,9);
}
int i=0;
while(i!=index)
{
if(!q->next&&flag==1)temp=q;
flag=1;
q=head;
head=head->next;
i++;
}
new*t=(new*)malloc(sizeof(new));
t->next=head;
int y=0;
t->data=num;
if(!(head&&q))
{
temp->next=t;
t->prev=temp;
y=1;
}
if(y==0)
{
q->next=t;
t->prev=q;
head->prev=t;
}
}
int main()
{
new * head=(new *)malloc(sizeof(new));
int A[5]={1,2,3,6,7};
create(head,A,5);
display(head);
int i=3;
insert(head,i,87);
display(head);
}
```