分段故障链表C++在末尾插入
Segmentation Fault Linked List C++ Insert at End
我的程序正在编译,但当我尝试运行此代码时遇到了seg错误。我想做的是将一个元素附加到链表的末尾。以下是我的应用程序正在做的事情:
int main()
{
linklist<int> l;
int i = 30;
l.insertEnd(i);
return (0);
}
下面是我的类中函数的实现:
template <class T>
void linklist<T>::insertEnd(T anItem)
{
if(this->headPointer = NULL)
{
headPointer = new node(anItem, NULL);
}
else
{
node* endPointer = headPointer;
while(endPointer->linkPointer != NULL)
{
endPointer = endPointer->linkPointer;
}
endPointer->linkPointer = new node(anItem, NULL);
}
};
最后,我的节点是如何设置的:
class node
{
public:
T dataItem;
node* linkPointer;
// construct a new node and initialize its attributes with the given parameters.
node(T i, node* l): dataItem(i), linkPointer(l)
{
};
};
node* headPointer;
};
template <class T>
void linklist<T>::insertEnd(T anItem)
{
if(this->headPointer == NULL) //you were assigning null instead of comparing
{
headPointer = new node(anItem, NULL);
}
//rest of the code here
试试这个
这句话中似乎有问题,这里不是比较,而是赋值。
if(this->headPointer = NULL)
使用此:
if(this->headPointer == NULL)
或
if(NULL == this->headPointer) // This is better way to compare.
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 预处理器:插入结构名称中的前一个行号
- 在未初始化映射的情况下,将值插入到映射的映射中
- 如何在c++中只将键插入到bimap的一侧
- 如何将结构插入到集合中并打印集合的成员
- C++json插入数组
- Visual Studio 2019:插入多个C++风格的单行注释
- nlohmann-json将一个数组插入到另一个数组中
- 有效地使用std::unordered_map来插入或增加键的值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 正在插入动态数组
- 插入或删除时获取usb的dos_name
- 叮叮当当在修复时插入多个"覆盖"说明符
- 链表c++插入,所有情况都已检查,但没有任何工作
- 将重物插入std::map
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 在数字之间插入 + 或 - 符号以使其等于整数
- 在字符串中插入空格
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?