链接的列表在类C 中实现,显示分段故障
Linked list implementation in classes c++, showing Segmentation fault
我知道在此循环中发生了分割故障:( while(temp != NULL){temp = temp->next;}
),但我不知道为什么。
#include<iostream>
using namespace std;
class zDepthList {
typedef struct node {
int data;
node* next;
node* prev;
} Node;
public:
zDepthList() {
head = NULL;
}
zDepthList(int array[], int length) {
Node *temp, *ptr;
int i = 0;
while(i != length - 1) {
temp = head;
ptr = new Node;
ptr->data = array[i];
i++;
ptr->next = NULL;
if(head == NULL) {
head = ptr;
ptr->prev = NULL;
}
else {
while(temp != NULL) {
temp = temp->next;
}
}
temp->next = ptr;
ptr->prev = temp;
}
}
void out(const char order) {
cout << head->data << endl;
return;
}
private:
Node *head;
};
对于初学者,您必须将head
初始化为NULL
。
之后,循环
else {
while(temp != NULL) {
temp = temp->next;
}
}
temp->next = ptr;
ptr->prev = temp;
指针temp
等于NULL
,因为它是中断循环的条件。因此,此语句
temp->next = ptr;
导致不确定的行为。
如果您有双链接列表,也很自然地引入数据成员tail
,很容易附加新节点。
因此您应该包括
class zDepthList {
//...
private:
Node *head, *tail;
};
在这种情况下,构造函数可以查看以下方式
zDepthList() : head( nullptr ), tail( nullptr )
{
}
zDepthList( const int a[], size_t n ) : head( nullptr ), tail( nullptr )
{
for ( size_t i = 0; i < n; i++ )
{
Node *tmp = new Node { a[i], nullptr, tail };
tail == nullptr ? head = tmp : tail->next = tmp;
tail = tmp;
}
}
这是一个指示的程序
#include <iostream>
class zDepthList {
typedef struct node {
int data;
node* next;
node* prev;
} Node;
public:
zDepthList() : head(nullptr), tail(nullptr)
{
}
zDepthList(const int a[], size_t n) : head(nullptr), tail(nullptr)
{
for (size_t i = 0; i < n; i++)
{
Node *tmp = new Node{ a[i], nullptr, tail };
tail == nullptr ? head = tmp : tail->next = tmp;
tail = tmp;
}
}
std::ostream & out( std::ostream &os = std::cout ) const
{
for (Node *current = head; current; current = current->next)
{
os << current->data << ' ';
}
return os;
}
private:
Node *head, *tail;
};
int main()
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
zDepthList l(a, sizeof(a) / sizeof(*a));
l.out() << std::endl;
}
程序输出是
0 1 2 3 4 5 6 7 8 9
您永远不会设置head
,而是访问它。这意味着它是非初始化的,这是UB。
您有2个ctors,只有在没有任何参数的情况下调用它。
head
。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 如果没有malloc,链表实现将失败
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 如何在c++中实现处理器调度模拟器
- 字符串-C++后显示的随机字符
- 继承期间显示未知行为的子类
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 使用简单类型列表实现的指数编译时间.为什么
- 显示实现最大利润的步骤
- 对于第二个本机函数,显示不舒适的LinkError:未针对.stringfromjni2()找到实现
- 如何在C++中实现按级别计数/显示节点的功能
- 链接的列表在类C 中实现,显示分段故障
- 从后到前显示使用链表实现的队列
- 如何正确实现类的显示函数
- sizeof不会显示实际大小,试图实现ip
- 在实现 OpenFileDialog 时,"System.IO.FileStream"显示在生成的编辑文本框中,而不是文件名和路径上。如何?
- 为什么这个C++Trie实现显示出奇怪的行为
- 使用铂库实现 c++ DLNA 字幕显示