-2

I created a private static variable that keeps track of the number of elements in the linked list.

struct node
{
        int data;
        node *next;
};    
class linkedList
    {
            private:
                    node *head,*tail;
                    static int listSize;
            public:
                linkedList()
                {
                    head=NULL;
                    tail=NULL;
                }
                void insert(int n)
                {
                        node *temp=new node;
                        temp->data=n;
                        temp->next=NULL;
                        if(head == NULL)
                        {
                                head=temp;
                                tail=temp;
                        }
                        else
                        {
                                tail->next=temp;
                                tail=temp;
                        }
                        linkedList::listSize+=1;
                }
    };
    void main()
    {
         linkedList l;
         l.insert(10);
         l.insert(20);
    }

The compiler throws an error when it reaches the line linkedList::listSize+=1;

error: ‘linkedList’ has not been declared.

Prasanth Ganesan
  • 541
  • 4
  • 14

1 Answers1

2

Once your typos corrected (inser(20) instead of insert(20) and : instead of ; in linkedList(), your program almost compiles.

There is just one thing missing: you need to implement the listSize variable somewhere for example by putting int linkedList::listSize; before main:

...
int linkedList::listSize;   /(/ <<< add this

void main()
{
  linkedList l;
  l.insert(10);
  l.insert(20);
}

But why are you using a static variable for counting the elements of the list? You probably want listSize to be an ordinary (non static) class member, just as head and tail:

class linkedList
{
private:
  node * head, *tail;
  int listSize;      // no static
public:
  ...

and drop the int linkedList::listSize; suggested before.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115