Reputation: 25
This is a code to make a linked list with 2 values- one user input and another 7.
#include<iostream>
#include<cstdlib>
using namespace std;
class node{
public:
node();
~node();
void printList();
void insert_front(int);
void delete_front();
private:
int data;
node *head;
node *next;
};
node::node()
{
head=NULL;
}
node::~node( ){//destructor
cout <<"destructor called";
while( head!= NULL) delete_front() ;
}
void node::delete_front(){
node *h=head;
if(head==NULL)
{
cout<< "Empty List.\n";
return;
}
head = head->next;
delete(h);
}
void node::printList()
{
node *h=head;
cout<< "Printing the list";
while(h!=NULL)
{
cout<< h->data;
cout<< '\n';
h->next= h->next->next;
}
}
void node::insert_front(int value){
node *temp = new node;
temp->data=value;
temp -> next = NULL;
if (head != NULL){
temp->next =head;
}
head= temp;
}
int main()
{
node ListX;
cout<< "enter integer";
int as;
cin>> as;
ListX.insert_front(as);
ListX.insert_front(7);
ListX.printList();
ListX.~node( );//call destructor to free objects
return 0;
}
Please tell the error in this as it shows an error while compiling it online on http://www.compileonline.com/compile_cpp_online.php and even on my laptop.
Upvotes: 1
Views: 466
Reputation: 47794
h->next= h->next->next;
What are you trying to achieve here ?
Change while
loop in void node::printList()
to:
while(h!=NULL)
{
cout<< h->data;
cout<< '\n';
h= h->next;
}
Upvotes: 3