In the Following code, Function Delete_item is not working properly. it only works when we use break; statement... if some can do it without using break; stetement then please share and eplain the method...
#include<iostream>
using namespace std;
struct node
{int info;
node *link;
};
class list
{private:
node *head, *current, *last, *newnode;
public:
list()
{head=NULL;
current=NULL;
last=NULL;}
void create_list_f(int);
void insertAtN(int, int);
void delete_item(int data);
void print();
};
void list::create_list_f(int data)
{
newnode=new node;
newnode->info=data;
newnode->link=NULL;
if(head==NULL)
{head=newnode;
last=head;
}
else
{last->link=newnode;
last=last->link;
}
}
void list::insertAtN(int data, int n)
{int i=1;
newnode=new node;
newnode->info=data;
newnode->link=NULL;
current=head;
if(n==1)
{newnode->link=head;
head=newnode;
}
else
{
while((i<n) &&(current)!=NULL)
{
if(i==n-1)
{newnode->link=current->link;
current->link=newnode;}
else
current=current->link;
i++;}
}
}
void list::print()
{current=head;
while(current!=NULL)
{cout<<current->info<<" ";
current=current->link;
}
}
void list::delete_item(int data)
{node *prev,*q;
q=head;
if(q->info==data)
{q=head;
head=head->link;
delete q;
}
else
{ q=head;
prev=head;
while(q!=NULL)
{
if(q->info==data)
{prev->link=q->link;
delete q;}
else
{prev=q;
q=q->link;}}
}}
void main()
{list list1;
int data,item, n;
char choice='y';;
while(choice=='y')
{
cout<<"enter Data"<<endl;
cin>>data;
list1.create_list_f(data);
cout<<"press y if you want to enter more data"<<endl;
cin>>choice;
}
cout<<"Enter the position where you want to insert data"<<endl;
cin>>n;
cout<<"Enter Data"<<endl;
cin>>data;
list1.insertAtN(data, n);
list1.print();
cout<<"Entr element to delete"<<endl;
cin>>item;
list1.delete_item(item);
cout<<"List:"<<endl;
list1.print();
system("pause");
}