I am learning C++ and trying to implement a singly linkedlist. Basically a linkedlist providing two simple methods, insert and display. Below is the code snippet --
class LinkedList {
public:
int data;
LinkedList *next;
LinkedList() {
}
LinkedList(int d) {
data = d;
}
void insert(int d) {
LinkedList temp = *this;
cout << "Calling insert "<< temp.data;
while (temp.next != NULL) {
cout << "Inside the while loop"<< temp.data;
temp = *temp.next;
}
temp.next = new LinkedList(d);
}
void display() {
LinkedList temp = *this;
cout << temp.data;
while (&temp != NULL) {
cout << temp.data;
temp = *temp.next;
cout << temp.data;
}
}
};
int main()
{
LinkedList head(1);
head.insert(2);
head.insert(3);
head.insert(4);
head.display();
return 0;
}
However, this insert method is not working as expected. Even after calling insert multiple times, it is never going inside the while loop and "Inside the while loop" is never getting printed. Could you guide what is wrong with my insert method?
LinkedList temp = *this;makes a copy and then you modify the copy.int main() { LinkedList x; x.insert(10); }-- you don't need any further code to see the issues.LinkedList temp = *this;creates a local copy ofthis. Hence,temp.next = new LinkedList(d);appends the new node to the local copy and is lost as soon as you leaveinsert().