Adding data in linked list using for loop

Vinod Patel picture Vinod Patel · Oct 31, 2013 · Viewed 8.2k times · Source

I want to add data into a linked list using for loop. what i expect is 1 2 3 4 5 6 7 8 9 10 O/P i'm getting is 1 1 1 1 1 1 1 1 1 1

#include <iostream>
using namespace std;
struct NODE
{
    int data;
    NODE *next;
};
int main()
{
    int i,j=0;
    NODE *start=NULL,*ptr,*temp;
    for (i=1;i<=10;i++)
    {
        ptr = new NODE;
        ptr->data=i;
        ptr->next=NULL;
        if(start==NULL)
            start=ptr;
        else
        {
            temp=start;
            while(temp->next!=NULL)
                temp=temp->next;
            temp->next=ptr;
        }
    }
    temp=start;
    while(temp->next!=NULL)
    {
        cout<<start->data<<"  ";
        temp=temp->next;
    }
    return 0;
}

what is wrong with this program??

Answer

Vlad from Moscow picture Vlad from Moscow · Oct 31, 2013

It is this loop that is wrong

temp=start;
while(temp->next!=NULL)
{
    cout<<start->data<<"  ";
    temp=temp->next;
}

Change it the following way

for ( temp = start; temp; temp = temp->next ) cout << temp->data << ' ';

Or if you want to use while-loop then

temp = start;
while ( temp )
{
    cout << temp->data << '  ';
    temp = temp->next;
}

Also instead of name temp I would use name next. For example

for ( NODE *next = start; next; next = next->next ) cout << next->data << ' ';