i want to insert node at nth position but when i press 1 to insert value program stops working means its not inserting value.
what is wrong in this code?
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
node *head,*temp,*p;
node *create(int);
node *insert(int,int);
node *delete(int);
main()
{
int n,opt,x,loc,val;char ch;
printf("Enter how many nodes");
scanf("%d",&n);
head=create(n);
display();
printf("\npress 1 to insert value\n");
printf("\npress 2 to delete value");
scanf("%d",&opt);
if(opt==1)
{
printf("Enter value which u want to insert");
scanf("%d",&x);
printf("Enter location where u want to insert this value");
scanf("%d",&loc);
head=insert(x,loc);
display(); }
else if(opt==2)
{
printf("Enter value which u want to delete");
scanf("%d",&val);
head=delete(val);
display();
}
}
node *create(int n)
{
int i;
head=(node *)malloc(sizeof(node));
printf("enter data");
scanf("%d",&head->data);
p=head;
for(i=1;i<n;i++)
{
temp=(node*)malloc(sizeof(node));
printf("Enter data");
scanf("%d",&temp->data);
temp->next=NULL;
p->next=temp;
p=temp;
}
return head;
}
display()
{
p=head;
while(p!=NULL)
{
printf("%d\t",p->data);
p=p->next;
}
}
node *insert(int x,int loc)
{
node *temp2;
int i,cnt=0;
p=head;
while(p!=NULL)
{
cnt++;
p=p->next;
}
if(loc>cnt+1)
printf("Not posible\n");
else
{
temp2=(node*)malloc(sizeof(node));
temp2->data=x;
temp2->next=NULL;
for(i=1;i<loc-1;i++)
p=p->next;
temp2->next=p->next;
p->next=temp2;
}
return head;
}
node * delete(int val)
{
node *q;
if(val==head->data)
{
q=head;
head=q->next;
q->next=NULL;
free(q);
return head;
}
p=head;
q=head->next;
while(q!=NULL && val!=q->data)
{
p=p->next;
q=q->next;
}
p->next=q->next;
q->next=NULL;
free(q);
return head;
}
delete function works...only problem is in insert function
someone help me please!!!