Reputation: 19
This is my code for creating a singly-linked list in C++.
The function del_alt() deletes every alternate element starting from the second element.
The compiler gives no error as such , but during run the program terminates abruptly after showing the original list.
I have tried my best to find the possible errors but can't find any.
Help appreciated.
Cheers.
#include<iostream>
using namespace std;
class Node
{
public:
Node()
{
next=0;
}
Node *next;
int info;
};
class List
{
private:
Node *head,*tail;
public:
List()
{
head=0;
tail=0;
}
void del_alt();
void add_to_head(int);
void show_list();
};
void List :: del_alt()
{
if(!head||(head==tail))
return;
else
{
Node *current,*after,*ptr;
for(current=head,after=head->next;current!=0;current=current->next,after=current->next)
{
ptr=after;
current->next==after->next;
if(ptr==tail)
tail=current;
delete ptr;
}
}
}
void List :: add_to_head(int el)
{
Node *ptr;
ptr->info=el;
if(!head)
{
ptr->next=0;
head=tail=ptr;
}
else
{
ptr->next=head;
head=ptr;
}
}
void List::show_list()
{ Node *ptr;
cout<<"\n\n";
ptr=head;
while(ptr!=0)
{
cout<<"\t"<<ptr->info;
ptr=ptr->next;
}
}
int main()
{
List l;
int el;
char ch;
cout<<"\n\n\t\t enter elements\n\n\t";
do
{
cin>>el;
l.add_to_head(el);
cout<<"\n\t want to enter more ? (y/n) \n";
cin>>ch;
}while(ch=='y'||ch=='Y');
cout<<"\n\t Original list -> \n";
l.show_list();
l.del_alt();
cout<<"\n\t After deletion -> \n";
n.show_list();
cout<<"\n\n \\===============================================";
}
Upvotes: 0
Views: 48
Reputation: 1635
The problem comes from the non-initialization of ptr in the method add_to_head.
Node *ptr;
ptr->info=el
At least ptr should be a new allocated cell
Node *ptr = new Node;
ptr->info=el
Upvotes: 1