在C++中实现链表时的运行时(或逻辑)错误
runtime ( or maybe logical ) error when implementing linked list in c++
链表是一种线性数据结构,其中每个元素都是一个单独的对象。列表的每个元素(我们称之为节点)都由两个项目组成 - 数据和对下一个节点的引用。最后一个节点具有对 null 的引用。
所以我试图用C ++制作一个简单的链表(不是双重或循环),这是我的代码。我用Xcode运行它,语法没有问题。我添加了一个键为 1 和数据"ASD"的节点。我试图打印列表的元素,但我看到的是:(LLDB)
怎么了?
提前谢谢。
#include <iostream>
#include <string>
using namespace std;
class node {
friend class linkedlist;
private:
int key;
string data;
node *next;
public:
node(int k,string d){
this->key=k;
this->data=d;
}
};
class linkedlist{
private:
node *head;
node *last;
public:
linkedlist(){
this->head=NULL;
this->last=NULL;
}
inline bool is_empty() {return head==NULL;}
void print(){
cout<<"n";
node *current;
for(current=this->head;current!=NULL;current=current->next){
cout<<"("<<current->key<<","<<current->data<<")"<<" ";
}
cout<<"n";
}
void insert(int k,string d){
node *new_node=new node(k,d);
this->last->next=new_node;
this->last=new_node;
if(this->is_empty()) this->head=new_node;
}
};
int main()
{
linkedlist *list=new linkedlist();
list->insert(1,"asd");
list->print();
return 0;
}
在insert
函数中,您尝试访问 NULL 对象:
this->last->next=new_node;
您的列表为空,即 head
和last
为空。
我没有
分析列表实现,但也许这很重要:list->insert(1, string("asd"));
相关文章:
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 对单向链表进行排序时出现运行时错误
- 为什么此代码存在运行时错误?
- 你能解释一下什么运行时错误是如何解决它的吗?
- 如何修复分段错误运行时错误
- C++,弹出调试断言失败窗口,我得到矢量迭代器不兼容的错误运行时
- VBA 中的 Qt5 Dll,错误运行时错误 453
- 错误:运行时检查失败 #2 - 变量周围的堆栈已损坏
- 为什么我在没有calloc函数的情况下得到错误运行时
- 我不断收到函数初始化错误.(运行时检查失败 #3)
- C++11 线程错误运行时
- SIGSEGV错误(运行时错误)
- Visual Studio c++ MSVCR100.dll错误运行时
- 运行时错误 - C++ 运行时检查失败 #2 - 变量"theArray"周围的堆栈已损坏
- OpenGl的错误.运行时立方体顶点位置错误
- c++编程错误-运行时错误