我不明白我的代码有什么问题:
//Inserting n nodes, then print their values
#include <iostream>
#include <string>
using namespace std;
//Defining a node and it's head pointer
struct node
{
int data;
node *next;
};
node *head=NULL;
node *link;
node *tmp;
int main()
{
int n;
cin>>n;
while (n>0)
{
//Insert n nodes into the list
link=new node;
if (head==NULL)
{
head=link;
}
cin>>link->data;
link=link->next;
n--;
}
link=NULL;
//print data present in those n nodes
tmp=head;
while (tmp!=NULL)
{
cout<<tmp->data;
tmp=tmp->next;
}
return 0;
}
代码的第一部分定义了一个节点。
第二部分(main 函数的开头)是创建一个包含 n 个节点的链表的代码。所以我插入了 n 个节点。
最后,我使用指针 tmp 输出它们。但是,我没有得到数据值,而是得到了一个无限循环。这是怎么回事?
谢谢
最佳答案
#include <iostream>
#include <string>
using namespace std;
//Defining a node and it's head pointer
struct node
{
int data;
node *next=NULL;
};
node *head=NULL;
node *link;
node *tmp;
int main()
{
int n,limit;
cin>>n;
limit=n;
while (n>0)
{
tmp=link;
link=new node;
link->next=NULL;
cin>>link->data;
if (head==NULL)
{
head=link;
}
if(n!=limit) //check whether tmp is null initially tmp will be null for first element
{
tmp->next=link;
}
n--;
}
//print data present in those n nodes
tmp=head;
while (tmp!=NULL)
{
cout<<tmp->data<<"\n";
tmp=tmp->next;
}
return 0;
}
关于c++ - 在链表中插入 'n' 节点并打印其数据(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35824414/