c++ - 不显示任何输出
问题描述
我在用 c++ 编写链接列表实现时遇到了一个问题。每当我尝试添加一个元素时,他遵循的代码都不会显示任何输出。代码有什么问题
#include<iostream>
using namespace std;
struct Node {
int data;
struct Node* ptr;
Node(int val) {
data = val;
ptr = NULL;
}
};
void addItem(struct Node* head, int val) {
struct Node* n = new Node(val);
if(head == NULL){
head = n;
return;
}
struct Node* cur = head;
while(cur->ptr != NULL){
cur = cur->ptr;
}
cur->ptr = n;
}
void printList(struct Node* head) {
struct Node* cur = head;
while(cur != NULL) {
cout << cur->data << " ";
cur = cur->ptr;
}
}
int main() {
struct Node* head = NULL;
addItem(head, 1);
addItem(head, 2);
addItem(head, 3);
addItem(head, 4);
printList(head);
return 0;
}
当我运行程序时,它在终端上什么也没有显示。
输出:
[Running] cd "c:\Users\Sonu\" && g++ LinkedList.cpp -o LinkedList && "c:\Users\Sonu\"LinkedList
[Done] exited with code=0 in 3.436 seconds
解决方案
您应该通过head
双指针或引用传递。否则它将只是函数参数的一个副本,当从函数中出来时会被销毁。
void addItem(Node** head, int val) {
Node* n = new Node(val);
if(*head == NULL){
*head = n;
return;
}
Node* cur = *head;
while(cur->ptr != NULL){
cur = cur->ptr;
}
cur->ptr = n;
}
// ...
addItem(&head, 1); // take the address with &
或者
void addItem(Node*& head, int val) {
Node* n = new Node(val);
if(head == NULL){
head = n;
return;
}
Node* cur = head;
while(cur->ptr != NULL){
cur = cur->ptr;
}
cur->ptr = n;
}
// ...
addItem(head, 1); // no change needed
推荐阅读
- spring - 当将访问类型从公共更改为机密时,在社交登录中的 keycloak 中将您重定向太多次
- python - 使用带有日期时间数据的 numpy digitize
- facebook - 单击链接时将用户带出 Facebook 浏览器
- asp.net - 属性“TargetFrameworkAttribute”不能多次应用
- google-tag-manager - 当标签管理器具有与错误消息相同的 div 类时,如何在标签管理器中跟踪表单提交?
- xml - 火花-XML;在读取时使用显式模式从 S3 读取。XML中的数组类型问题
- c# - 通过 cmd 或 powershell 打开资源管理器并选择文件(文件路径较长)
- pandas - 从更改日期开始,熊猫按 +7 天的使用时间分组
- android - Jetpack Compose - 具有最大宽度的项目的 HorizontalPager 项目间距/填充
- java - 具有安全套接字的 Java HTTPS 客户端