Search code examples
c++linked-listis-empty

C++ Linked List isEmpty Function


I want to check, whether a linked list in C++ is empty or not. I have following class:

class IntLinkedList
{
    private:
        struct LinkedListNode        // Structure for linked list
        {
            int value;
            struct LinkedListNode *next;
        };
        LinkedListNode *head;       // List head pointer

    public:
        IntLinkedList(void)         // Constructor
        { head = NULL; }

        ~IntLinkedList(void);       // Destructor
        void AppendNode(int);
        void InsertNode(int);
        void DeleteNode(int);
        void DisplayList(void);
        bool isEmpty(LinkedListNode*);
};  

// isEmpty function
bool IntLinkedList::isEmpty(LinkedListNode *node)
{
    bool status;
    node = head;
    if ( node->next == NULL )
        status = true;
    else
        status = false;
    return status;  
}  

But I can't use this function in other class via an object of the same class.

How can I check the empty list using a function that would be accessible in another class through the object of the same class?


Solution

  • The error you are getting is caused by the fact that you declared your function as bool isEmpty(LinkedListNode) but you are trying to define it as bool isEmpty(LinkedListNode*). The difference is that in the definition you have a pointer, while in the declaration there is just an object. You have to pick one, as these are completely different things.

    That said, I don't see why you need the argument at all to check whether your list is empty. Just drop the argument altogether and use if ( head->next == NULL ) - non-static member functions are always called through an instance of the class.

    Just for completeness, first item in your list is pointed to by head, so in order to check if there is anything in the list, you should check if it is a null pointer:

    bool IntLinkedList::isEmpty() const
    {   //added const for const-correctness, should be added to declaration as well
        return head == nullptr;
    }