c++ - LinkedList 在 gcc 编译器中无法正常工作
问题描述
所以我正在使用 mingwx64 编译器和 vscode 编辑器,但是显示功能无法正常工作,但是当我尝试在 main() 函数中显示与 arr.display() 相同的逻辑时,它可以工作。我尝试在 onlinegdb 网站上运行相同的代码,它按预期运行。是 gcc 错误还是我不知道的功能?
#include <iostream>
using namespace std;
class nodee
{
public:
int data;
nodee *next;
};
class ll
{
public:
nodee **head = NULL;
nodee **push(int no = 1)
{
nodee *node;
int n;
if (head != NULL)
{
node = *head;
while ((*node).next != NULL)
{
node = (*node).next;
}
while (no--)
{
nodee *new_node = new nodee();
cout << "Enter the element : ";
cin >> n;
(*node).next = new_node;
new_node->data = n;
new_node->next = NULL;
node = (*node).next;
}
}
else
{
nodee *first = new nodee();
head = &first;
node = *head;
cout << "Enter the element : ";
cin >> n;
first->data = n;
no--;
while (no--)
{
nodee *new_node = new nodee();
cout << "Enter the element : ";
cin >> n;
(*node).next = new_node;
new_node->data = n;
new_node->next = NULL;
node = (*node).next;
}
}
return head;
}
void display()
{
nodee *node = *head;
while (node->next != NULL)
{
cout << node->data<<endl;
node = node->next;
}
cout<<node->data<<endl;
}
};
int main()
{
ll arr;
arr.push(5);
arr.display();
return 0;
}
解决方案
错误是head = &first;
,您正在使用指向局部变量 as 的指针,该指针在函数head
后无效。push
解决方案是head
只做一个nodee *
,你不需要额外的*
:
#include <iostream>
using namespace std;
class nodee
{
public:
int data;
nodee *next;
};
class ll
{
public:
nodee *head = NULL;
nodee *push(int no = 1)
{
nodee *node;
int n;
if (head != NULL)
{
node = head;
while ((*node).next != NULL)
{
node = (*node).next;
}
while (no--)
{
nodee *new_node = new nodee();
cout << "Enter the element : ";
cin >> n;
(*node).next = new_node;
new_node->data = n;
new_node->next = NULL;
node = (*node).next;
}
}
else
{
nodee *first = new nodee();
head = first;
node = head;
cout << "Enter the element : ";
cin >> n;
first->data = n;
no--;
while (no--)
{
nodee *new_node = new nodee();
cout << "Enter the element : ";
cin >> n;
(*node).next = new_node;
new_node->data = n;
new_node->next = NULL;
node = (*node).next;
}
}
return head;
}
void display()
{
nodee *node = head;
while (node->next != NULL)
{
cout << node->data<<endl;
node = node->next;
}
cout<<node->data<<endl;
}
};
int main()
{
ll arr;
arr.push(5);
arr.display();
return 0;
}
推荐阅读
- mysql - 如何撤销一个模式(crm)和用户(cus)中一张表的更新授权
- ios - 如何使用标头中的 Token 和 Alamofire 中的基本身份验证发出请求?
- java - 装饰器模式实现 - 扩展与实现
- amazon-web-services - 从 Lambda 在 EC2 上运行 Get 命令
- asp.net - 重写 URL 中间
- html - 将 doc 转换为 html 图形或形状时未转换为 html 格式
- php - 找不到驱动程序 Laravel + Xampp Ubunutu
- labview - Labview Vi 的 exe 文件无法通过 Python 脚本运行
- javascript - Rx DebounceTime 不起作用
- android - 向 Crashlytics 报告 Firebase 崩溃