error at the final result of a linked list

what i have to do to have a wright result?
the out put is always one number like
5555555 or 666666

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
using namespace std;

int n;
struct node
{
    int  data;
    node *next;
};
int main()
{
        node *temp;
        temp= new node;
        cout<<"please enter the size of the linked list"<<endl;
        cin>>n;

        cout<<"NOW BUILD IT"<<endl;
        for (int i=0 ; i< n ;i++)
        {
            cin>>temp->data;
        }
      temp->next=NULL;
        cout<<" the linked list"<<endl;
        for (int i=0 ; i< n ;i++)
        {
           cout<<temp->data;

        }
}

To build you linked list, you'll need some dynamic allocation. Inside that loop, you are reassigning the value of "data" over and over again instead of assigning the value to a new node.

Each time you enter a new value, you need a allocate a new mode and assign the appropriate value to the node that you just created.
You'll then have to iterate through the list and delete what you've used.

There are some STL stuff you could use, but I assume you are supposed to make your own linked list with this.

Make sure that every new is matched with a delete or you'll get memory leaks.
Topic archived. No new replies allowed.