Reputation: 573
I'm trying to create a recursive Linked List. At the moment I simply provide the class with two methods, one for tail insertion and a print. I don't understand why it doesn't print anything. I think the main problem is on recInsert(node,key) method who interprets the head node always as NULL. What I'm doing wrong?
I want to print the sequence 8->7->12->22
Here's my code:
template<class H>class NodeList{
private:
NodeList<H> *prev,*next;
H* key;
public:
NodeList(NodeList<H> *next,H *key){
this->next = next;
this->key = new H(*key);
}
NodeList<H> *getPrev(){return prev;}
NodeList<H> *getNext(){return next;}
void setPrev(NodeList<H> *prev){this->prev = prev;}
void setNext(NodeList<H> *next){this->next = next;}
void setKey(H *key){this->key = new H(*key);}
H *getKey(){return key;}
};
template<class H>class List{
private:
NodeList<H> *head;
public:
List(){
head = NULL;
}
NodeList<H>* insTail(NodeList<H> *nod,H *key){
if(nod == NULL){
nod = new NodeList<H>(nod,key);
}
else{
nod->setNext(insTail(nod->getNext(),key));
}
return nod;
}
List<H> *ins(H key){
insTail(head,&key);
return this;
}
void recPrint(NodeList<H> *head){
if(head == NULL){
return;
}
else{
cout<<*head->getKey();
recPrint(head->getNext());
}
}
void print(){
recPrint(head);
cout<<endl;
}
};
int main(){
List<int> *l = new List<int>();
l->ins(8)->ins(7)->ins(12)->ins(22);
l->print();
I've resolved adding a control on head node on insTail() method
NodeList<H>* insTail(NodeList<H> *nod,H *key){
if(head == NULL)
head = new NodeList<H>(NULL,key);
if(nod == NULL){
return new NodeList<H>(NULL,key);
}
else{
nod->setNext(insTail(nod->getNext(),key));
return nod;
}
}
Upvotes: 0
Views: 123
Reputation: 3477
You're almost there: head
needs to be assigned the result of insTail:
head = insTail(head,&key);
Upvotes: 1