【发布时间】:2021-10-29 03:21:07
【问题描述】:
我需要帮助来了解为什么我的链接列表方法不能按预期工作。
#include <iostream>
using namespace std;
class Node {
public:
int Data;
Node* Next;
Node(int data) {
Data = data;
Next = NULL;
}
};
void insertNodeAtEnd(Node* HEAD, int data) {
Node* it = HEAD;
if (HEAD == NULL) { HEAD = new Node(data); }
else {
while (it->Next != NULL) { it = it -> Next; }
it -> Next = new Node(data);
}
}
void printLinkedList(Node* HEAD) {
Node* it = HEAD;
while (it != NULL) {
cout << it->Data << endl;
it = it -> Next;
}
}
int main() {
Node* HEAD = NULL;
// Node* HEAD = new Node(0);
insertNodeAtEnd(HEAD, 5);
insertNodeAtEnd(HEAD, 2);
insertNodeAtEnd(HEAD, 10);
printLinkedList(HEAD);
return 0;
}
上面的main() 函数不起作用(即:没有输出,并且只要控件离开insertNodeAtEnd(),HEAD 就会一直重置为 NULL),我在 SO 上发现了类似的问题,解释了这一点是因为指针是按值传递的,这对我来说有部分意义。
如果指针作为值传递,当我在 main() 函数中将 Node* HEAD = NULL; 替换为 Node* HEAD = new Node(0); 时,为什么它会按预期工作?
如果我像 Node* HEAD = new Node(0); 一样初始化 HEAD,但在最初 HEAD = NULL 的情况下不会添加节点?通过使用pointer to pointer,我能够让它正常工作,但我不明白为什么这种方法不起作用。如果我没有正确解释我的问题,我很抱歉,如果需要任何澄清,请告诉我。
【问题讨论】:
-
我没有阅读所有内容,这可能无法回答您的问题,但
if (HEAD == NULL) { HEAD = new Node(data); }是内存泄漏。 -
@Brotcrunsher 我知道你说的是对的,因为 HEAD 没有保留新节点但内存从未释放,但我不明白为什么
标签: c++ pointers linked-list