<分区>
我在 C++ 中使用类时遇到一个奇怪的问题。
这是我的代码,用于将对象添加到我的链表中。我发现我的 V1 代码工作正常,但 V2 代码不工作,并且 printList 在 V2 中永远不会停止。谁能解释为什么会这样,因为我预计 V1 和 V2 代码应该输出相同的结果。
#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);
}