How to write _find method for Linked List?

I'm trying to learn how to write a linked list in C++. My book has the find method written like this...

~in the header~

ListNode* _find(size_t position);

~in the .cpp~

ListNode* LList::_find(size_t position)
{
    ListNode *node = head_;
    size_t i;

    for (i=0; i<position; i++){
        node = node->link_;
    }

    return node;
}

It all works fine, but I don't understand why the function has a pointer? As in, I don't understand why there is a * after ListNode. If someone could explain I'd appreciate it!

Upvotes: 0

Views: 82

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

First of all the function is invalid.

ListNode* LList::_find(size_t position)
{
    ListNode *node = head_;
    size_t i;

    for (i=0; i<position; i++){
        node = node->link_;
    }

    return node;
}

For example either head_ can be equal to NULL or the value of parameter position can be greater than the actual number of nodes in the list.

So the valid code could look the following way

ListNode* LList::_find(size_t position)
{
    ListNode *node = head_;

    for ( size_t i = 0; node && i < position; i++ ){
        node = node->link_;
    }

    return node;
}

As for your question then the list is built such a way that each node contains pointer to the next node. And the first bnode that is head_ also is a pointer. So it is simpler to return pointer from the function. If to return the object itself then in case if there is no target object it is not clear what to do except to throw an exception.

Upvotes: 0

brandonjsmith
brandonjsmith

Reputation: 246

The ListNode* in the method signature is the return type of the method. Your method is returning a pointer to a ListNode and the * character is used to indicate that the variable is a pointer. The reason you return a pointer is because a LinkedList, by definition, is a structure with pointers to the next node in the list.

Contrast a LinkedList with a simple array, where the elements are not pointers.

Upvotes: 1

Related Questions