simple linked list, how to insert

can you help me with this code

#include

using namespace std;

class LList
{

private:
	class Node{
        public:
            int price;
            Node * next;
    };
    Node * first;



public:

	LList()
	{
		first = NULL;
	}

	bool isempty()
	{
		if(first == NULL)
		return true;
		else
		return false;
	}


	void insert(int x)
	{

        if(isempty())
        {
            Node * n;
            n = new Node;
            n->price = x;
            n->next = NULL;
            first = n;
        }

	    else
        {
                Node * n;
                n = new Node;
                n->price = x;
                n->next = first->next;
                first->next = n;
        }

	}






	void erase()
	{


	}
	void print()
	{
	    Node * ptr;
	    ptr = first;
	    while(ptr != NULL)
        {
            cout << ptr->price << " ";
            ptr = ptr->next;
        }
        cout << endl;
	}

};
int main()
{
LList s;
s.insert(4);
s.print();

s.insert(1);
s.print();
s.insert(6);
s.print();
s.insert(10);
s.print();
s.insert(6);
s.print();

return 0;
}

the output of this program is

4

4 1

4 6 1

4 10 6 1

4 6 10 6 1

it must be

4

1 4

6 1 4

10 6 1 4

6 10 6 1 4

the first inserted node is somewhat wrong. can somebody help me with this one, i really find it hard to understand linked list using pointers

(this code is still incomplete)

Hi ramher237,

your insert function’s else part is wrong it must be

Node * n;

n = new Node;

n->price = x;

n->next = first;

first = n;

because first is pointer not node hence there is nothing like "first-> " first has reference of first node if you do first->price it means price of first node. if you do first->next it means link of (first)starting node but remember first is pointer not node it can hold only reference.

i hope it would help you but i didn’t check remaining function :frowning:

4 Likes