【发布时间】:2018-12-13 11:04:49
【问题描述】:
我正在尝试编写一个制作单个链表的代码。我想将所有数组元素放入每个节点并链接它们。但是当我运行我的代码时,我不断收到分段错误错误。我不明白为什么会收到此错误。 有人可以帮忙吗??谢谢!!
linked_list_main.cc
#include <iostream>
#include "linked_list.h"
int main() {
int array[5];
List<int> list(array, 5);
std::cout << list;
return 0;
}
template <class T>
class Node {
public:
T data;
Node<T>* next;
};
class List {
private:
Node<T> *head;
public:
List() : head(NULL) {};
~List() {
Node<T>* ptr;
for(ptr = head; ptr == NULL; ptr = head->next)
delete ptr;
}
List(T* arr, int n_nodes){
Node<T>* tmp = head;
for(int i = 0; i < n_nodes; i++ ) {
Node<T>* node = new Node<T>;
node->data = arr[i];
if(tmp != NULL) {
node->next = tmp;
tmp = node;
}
}
}
friend std::ostream& operator<<(std::ostream& out, List<T>& rhs) {
Node<T>* cur = rhs.head;
while(cur != NULL) {
if(cur->next == NULL)
out << cur->data << " ";
else
out << cur->data << ", ";
cur = cur->next;
}
}
};
【问题讨论】:
-
您可能需要更仔细地考虑一下您的析构函数在做什么。
-
我认为这会到达我创建的每个 Node
并删除动态分配的内存。不是它在做什么吗? -
“只要
ptr不指向任何东西,删除它指向的节点并移动到下一个节点”。你觉得这听起来对吗? -
一开始是一个nullptr,但它会移动到下一个,即head->next。我不明白。我不明白为什么这些不起作用,但这似乎很愚蠢,但我是一个初学者,我希望人们解释一下,而不仅仅是说发展自己..:(
-
如果
p是空指针,那么A)delete p无效,B)p->next无效。 (拿出铅笔和纸,用方框和箭头画出你的列表和变量。这是编写指针代码的最佳方法。)