Insert 'n' nodes in a linked list and print their data (C++)
<p>I don't understand what's wrong with my code here:</p>

<pre><code>//Inserting n nodes, then print their values 
#include &lt;iostream&gt;
#include &lt;string&gt;

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&gt;&gt;n;
    while (n&gt;0)
    {   
        //Insert n nodes into the list
        link=new node;
        if (head==NULL)
        {
            head=link;
        }
        cin&gt;&gt;link-&gt;data;
        link=link-&gt;next;
        n--;
    }
    link=NULL;

    //print data present in those n nodes
    tmp=head;
    while (tmp!=NULL)
    {
        cout&lt;&lt;tmp-&gt;data;
        tmp=tmp-&gt;next;
    }
    return 0;
}
</code></pre>

<p>The first part of the code defines a node.</p>

<p>The second part (beginning of main function) is code for creating a linked list with n nodes in it. So I insert n nodes.</p>

<p>Finally, I output them using the pointer tmp. However, instead of getting the data values, I just get an infinite loop. What is going on here?</p>

<p>Thanks</p>