【发布时间】:2021-09-16 03:12:40
【问题描述】:
当我在 dev C++ 中运行以下代码时,输出为空,即使在线编译器运行良好。我的代码中是否存在特定错误,或者我是否更改了开发 C++ 设置
#include<iostream>
#include<vector>
using namespace std;
class node //node definition
{
public:
int data;
node* next;
node(int value=0)
{
data=value;
}
};
node* insert(node* head,int data) //node insertion
{
node* ins=new node(data);
if(head==NULL)
{
return ins;
}
else
{
node* ptr=head;
while(head->next!=NULL)
head=head->next;
head->next=ins;
ins->next=NULL;
return ptr;
}
}
void print(node* head) //printing the values of linked list
{
while(head!=NULL)
{
cout<<head->data<<" ";
head=head->next;
}
}
int main()
{
vector <int> a{1,2,3,6,8};
node* list=NULL;
for(int x:a)
{
list=insert(list,x);
}
print(list);
}
谁能解决这个问题?
【问题讨论】:
-
长话短说:我建议在
print函数的末尾添加std::cout << std::endl;。 -
短篇小说:您不会默认初始化结构的
next成员。因此,当您第一次调用insert时,new结构的next成员可以是任何东西。在线编译器可能会意外地给出nullptr(零)值,但您不能依赖它。 -
另外,我建议检查您调用的 exe 文件是否正确。也许它会在某个调试或其他子目录中。请检查您的编译器以获取正确的输出路径设置。只是也许。 . .
-
No head no print,head为null时不分配head。
标签: c++ algorithm data-structures nodes dev-c++