Hi everyone,
I'm facing problem in deleting a node in del() used in my program.
Suppose, i've added a city as Delhi, and at the time of deleting, i type the name as delhi, the compiler gives a processor fault. But, i want it to display the line number 95.
I found out that there is error in while part in line number 85, but i dont know how to overcome that problem.
Anyone there to help me out with this????????????????????????
NOTE: I dont want to use any extra integer to detect the position.
My program:
#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<alloc.h>
struct city
{
char c[30];
struct city *next;
}*head=NULL,*tail=NULL;
void add();
void del();
void ins();
void disp();
void main()
{
int n;
while(1)
{
XY:
printf("\n\nLIST OF CITIES\n^^^^^^^^^^^^^^");
printf("\n1. Add a city.");
printf("\n2. Delete a city.");
printf("\n3. Insert a city.");
printf("\n4. Display.");
printf("\nEnter your choice.. ");
scanf("%d",&n);
switch(n)
{
case 1: add(); break;
case 2: del(); break;
case 3: ins(); break;
case 4: disp(); break;
default: printf("See the options BHOSDI KE");
printf("\npress enter to re-enter");
if(getch()=='\r')
{
clrscr();
goto XY;
}
}
printf("Do you want to continue?? (Y/N) ");
if(getche()=='y'||getche()=='Y')
continue;
else if(getche()=='n'||getche()=='N')
break;
}
}
void add()
{
char name[30];
printf("Enter the name of city: ");
scanf("%s",name);
struct city *curr;
curr=(struct city *)malloc(sizeof(struct city));
strcpy(curr->c,name);
if(head==NULL)
{
head=curr;
tail=curr;
tail->next=NULL;
}
else
{
tail->next=curr;
tail=curr;
tail->next=NULL;
}
}
void del()
{
XY:
char del_c[30];
printf("Enter the name of city to be deleted: ");
scanf("%s",del_c);
struct city *tmp,*prev;
tmp=head;
if(strcmp(del_c,head->c)==0)
{
head=head->next;
free(head);
}
else
{
while(strcmp(del_c,tmp->c)!=0)
{
prev=tmp;
tmp=tmp->next;
}
prev->next=tmp->next;
free(tmp);
}
if(strcmp(del_c,head->c)!=0||strcmp(del_c,tmp->c)!=0)
{
printf("City is not there in list");
goto XY;
}
}
void ins()
{
char ins_c[30]; int pos,m=1;
printf("Enter the position where you want to insert= ");
scanf("%d",&pos);
printf("Enter the city to be inserted: ");
scanf("%s",ins_c);
struct city *tmp,*curr;
curr=(struct city *)malloc(sizeof(struct city));
tmp=head;
strcpy(curr->c,ins_c);
while(m<pos-1)
{
tmp=tmp->next;
}
curr->next=tmp->next;
tmp->next=curr;
}
void disp()
{
struct city *ptr;
for(ptr=head;ptr!=NULL;ptr=ptr->next)
{
printf("\n\n%s",ptr->c);
}
printf("\n\n");
}