#include<iostream>
using namespace std;
struct node{
int data; // structure for each node of list
node *p;
};
class LinkedList{
node *head,*tail;
public:
LinkedList(){ //empty LinkedList used for overall structure
head=NULL;
tail=NULL;
}
void addnode(int x);
void show();
};
void LinkedList::addnode(int x){
node *temp=new node;
temp->data=x;
temp->p=NULL;
if(head==NULL){ //linkedList is empty therefore temp is both head and tail now
temp=head;
temp=tail;
}
else{
tail->p=temp;
tail=temp;
}
}
void LinkedList::show(){
node *temp;
temp=head;
while(temp!=NULL){
cout<<endl<<temp->data<<endl;
temp=temp->p;
}
}
int main(){
LinkedList l;
cout<<"Welcome to Linkedlist creation\n";
int choice;
cout<<"To add a node press 1,\nTo view your list press 2\n";
cin>>choice;
switch(choice){
case 1:
int data;
cout<<"Enter the data to be added: ";
cin>>data;
l.addnode(data);
break;
case 2:
l.show();
}
}
Plz tell me what's wrong in my code..! I need to understand whats wrong in my approach... I referred to a number of others sources and most are same just like mine, but the show() is not at all working... plz dont direct to other posts or plz tell me my mistake before doing that..
edited: sorry everyone for the typo, I mean the same if(head==null) and not =; i checked my code for the same and it was only wrong here, still same issue
Your LinkedList::addnode
has following errors:
if(head=NULL){
is wrong. =
is an assignment operator in C++ and it will set head
to NULL
and will be evaluated to false
. This will have tail->p=temp;
with tail = NULL
and it will lead to Segmentation Fault.temp=head; temp=tail;
is also wrong. It is overwriting the pointer to the newly created node by something, creating memory leak.The function should be:
void LinkedList::addnode(int x){
node *temp=new node;
temp->data=x;
temp->p=NULL;
if(head==NULL){ //linkedList is empty therefore temp is both head and tail now
head=temp;
tail=temp;
}
else{
tail->p=temp;
tail=temp;
}
}
Also your class LinkedList
doesn't follow The Rule of Three, so pointers are copied when the object is copied and it may be cause of trouble. Be careful when you develop your program more.
One more point is that your main()
can do only one of node insertion and printing, so you cannot print LinkedList
with nodes added.
You may want a loop like this:
int main(){
LinkedList l;
cout<<"Welcome to Linkedlist creation\n";
int choice;
for(;;){
cout<<"To add a node press 1,\nTo view your list press 2\n";
if(!(cin>>choice))break; // exit when reading failed
switch(choice){
case 1:
int data;
cout<<"Enter the data to be added: ";
cin>>data;
l.addnode(data);
break;
case 2:
l.show();
}
}
}