I am trying to write a basic link list, so that I can understand how to implement it in C++. The tutorial I read was extremely advanced (giving more code than needed to understand and not explaining really how). So i tried to write this simple linked list:

#include <iostream>

using namespace std;

struct node
{
    int data;
    node *next;
}*p;

int main()
{
    int num;
    while(true)
    {
        node *l = new node;
        l->next = 0;

        cout<<"Enter numbers (0 to stop): ";
        cin>>num;

        if(!num)
            break;

        if(p == NULL)
        {
            l->data = num;
        }
        else 
        {
            node *tmp = new node;
            tmp->data = l->data;
            tmp->next = 0;
            l->next = new node;
            l->data = tmp->data;
            delete tmp;
        }

        cout<<l->data<<endl;
    }
    cin.get();
}

But it dosnt work. I think that I might not create then new 'node' correctly...
So can someone please explain to me how implement my code correctly?

Thanks in advance...

I'd suggest this tutorial as it covers a lot of information, but builds up to it with just enough code to get the job done. It's written in C, but a conversion to C++ is trivial.

Concerning your immediate problem, I notice that you never modify p, even though it being NULL or not is a key component of the algorithm. Assuming p is supposed to be your head node, that means you need something more like this to build the list in reverse:

#include <iostream>

using namespace std;

struct node
{
    int data;
    node *next;
} *p;

int main()
{
    node *tmp;

    cout << "Enter numbers (0 to stop): ";

    while (true)
    {
        int num;

        if (!(cin >> num) || !num) {
            break;
        }

        tmp = new node;
        tmp->data = num;
        tmp->next = p;
        p = tmp;
    }

    // Test the list outside of the creation loop
    for (tmp = p; tmp; tmp = tmp->next) {
        cout << tmp->data << (tmp->next ? "->" : "\n");
    }

    // Ignore list destruction for now
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.