I encounter a strange issue when using class in C++.
Here is my code to add object the my linked list. I found that my V1 code works correct but V2 code doesn't and the printList can never stop in V2. Do anyone can explain why it is the case, since I expect V1 and V2 code should output the same outcome.
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node() {
cout << "Node object is being created" << endl;
}
};
void printList(Node *node) {
while(node != NULL) {
cout << node->data << ",";
node = node->next;
}
cout << endl;
}
void push(Node **node, int data) {
// // working V1 start
// Node *newNode = new Node();
// newNode->data = data;
// newNode->next = *node;
// *node = newNode;
// // working V1 end
// not working V2 start
Node newNode;
newNode.data = data;
newNode.next = *node;
*node = &newNode;
// not working V2 end
}
int main() {
Node *a = NULL;
push(&a, 15);
push(&a, 10);
printList(a);
}