I'm trying to implement a simple list in C++ but I'm stuck with writing the add function
When adding one element it works fine but then it just keeps adding the element indefinitely
This is weird because I'm making sure to only add to the tail of the linked list and the last element is always NULL.
The result is correct only if we add to a list containing just one element.
#include <iostream>
using namespace std;
class List {
int value;
public:
List(int value);
List* next;
List* tail();
void add(int value);
void reverse();
void echo();
};
List::List(int value){
List::value = value;
List::next = NULL;
}
List* List::tail(){
List* tail = this;
for(;tail->next!=NULL; tail = tail->next);
return tail;
}
void List::add(int value)
{
List next (value);
List* tail = List::tail();
tail->next = &next;
}
void List::echo()
{
cout << List::value << " ";
if(next!=NULL){
next->echo();
}
}
int main(){
List list (3);
list.add(1);
list.add(2);
list.echo();
}
&nextis a pointer to a local variable so causes undefined behaviour when it is dereferenced later