c++ - 在链表中插入 'n' 节点并打印其数据(C++)

标签 c++ data-structures linked-list

我不明白我的代码有什么问题:

//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/

相关文章:

c++ - 无法理解 "list<int>::iterator i;"

c++ - CUDA-优化表面检测内核

arrays - Swift 中的链表

c++ - 制作 C++ 哈希表的最佳策略,线程安全

c++ - 不正确的观察矩阵

arrays - 有没有更优雅的方式来做到这一点?

python - 如何在 Python 中存储键值和值键?

algorithm - 数据结构 : If Heaps are trees, 为什么它们在内部用列表或数组实现?

c - 链表缺失元素

java - Java中如何实现循环链​​表?