Reputation: 35
I created a Linked List class ,everything works just fine but when i run Delete_At Function it get crashed ! , no syntax errors given , it's logical,i really don't know what i am missing
here is the code :
#include <iostream>
using namespace std;
struct node{
int info;
node *link;
};
class Linked_List{
private :
int count;
node *first;
node *last;
node *current;
public:
Linked_List() {
count=0;
first=NULL;
last=NULL;
}
void Initialize_List(){
cout<<"Enter Number OF Nodes"<<endl;
cin>>count;
first=last=current=new node;
for(int i =0;i<count;i++){
cout<<"Enter New Node Info :"<<endl;
cin>>current->info;
last->link=current;
last=current;
current=new node;}
last->link=NULL;
}
void Insert_At (int loc,int element){
for (current=first;current!=NULL;current=current->link){
if (current->info==loc){
node *newnode= new node;
newnode->info=element;
newnode->link=current->link;
current->link=newnode;
count++;}
}
if(current==last){
node *newnode= new node;
newnode->info=element;
last->link=newnode;
last=newnode;
newnode->link=NULL;}
}
void Delete_At(int loc){
bool found;
node *p=new node;
if(first ==NULL)
cout<<"can't delete from empty list"<<endl;
else {
found = false ;
current=first;
p=first->link;
while (p!=NULL){
if(p->info!=loc){
current=p;
p=p->link;}
else found = true;}
if (found) {
current->link=p->link;
count--;
delete p;} }}
};
void main (){
Linked_List obj;
obj.Initialize_List();
obj.print();
obj.Insert_At(3,10); cout<<"item inserrted"<<endl;
obj.print();
obj.Delete_At(3); cout<<"item deleted"<<endl; //lets say i have number 3 in my
list.
obj.print();
}
Upvotes: 0
Views: 51
Reputation: 8514
Your while loop loops until p
is NULL, even if the node is found. Then you immediately dereference p
in the current->link=p->link
line, when p
is guaranteed to be NULL.
You need to break out of the while loop when you have found the right node. Putting && !found
into the while clause would do it.
Note that this is made harder to spot by the lack of indentation, I don't know if that is due to the cut-and-paste or if it is how you wrote it.
Upvotes: 1