c++ - 为什么我的链表实现不起作用?
问题描述
编译后 - 当 cmdl 弹出时 - 它不会终止并像等待输入一样等待
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
node *next;
};
class LinkedList{
private:
struct node *head;
struct node *tail;
public:
LinkedList(int val1,int val2){
head->next = tail;
head->data = val1;
//tail->next = NULL;
//tail->data = val2;
}
add(int val){
struct node *n = new node;
n->next = head->next;
head->next = n;
n->data = val;
}
display(){
struct node *ptr = head;
while(ptr->next!=NULL){
cout<<ptr->data;
ptr = ptr->next;
}
}
};
int main(){
LinkedList l(1,3);
for(int i = 0;i<5;i++) l.add(i);
l.display();
}
是什么阻止了代码按预期执行?我尝试了一些内置函数来测试代码,但是它们都没有响应调用并生效。
解决方案
运行此代码时出现访问冲突。
添加
head = new node;
在您的构造函数的开头修复了这个问题。
我也会像这样显式地将 head 和 tail 初始化为 null
private:
struct node *head = NULL;
struct node *tail = NULL;
否则,它们将充满垃圾值,您可能会在显示代码中获得无限循环。
推荐阅读
- rust - 如何从 zip 文件中读取特定文件
- c# - 通过中间映射将字典分组到其他字典
- python - 如果 python 和 sql 不存在新记录,则将新记录插入表中
- c# - 如何防止 WPF 应用程序中的开始菜单固定
- swift - 在 for 循环中每 3 次执行一次操作
- windows-10 - 展开命令行参数自动热键
- swift - 日期比较总是返回 true - Swift
- list - Flutter:通过在构建小部件时创建一个大列表来提高性能
- sql - 为什么 Postgres 不接受我的计数列?
- python - 当我在 Python 3.9 中使用 Requests 请求文档页面时,我会发出多少个 http 请求?