Function to return total data within a linkedlist C++
Trying to implement a function in my linkedlist class that will return total amount of data stored within the list. i.e. linkedlist of 5, 10, 20 total would return 35.
My node class contains the getNextPtr and getData methods.
I implement a new Node and call it currentPtr and make it point to headPtr.
On compile i get: "36-request for member getNextPtr in currentPtr which is of non class type"
It's the same for 38 and 40, with 38 being the getData in currentPtr.
Not quite sure what I'm missing...
int LinkedList::getTotal()
{
int total = 0;
Node *currentPtr = headPtr;
(36) while(currentPtr.getNextPtr() != NULL)
{
(38) total += currentPtr.getData();
(40) currentPtr = currentPtr.getNextPtr();
}
return total;
}
The idea is to travel through the linked list until it reaches tailptr which will point to null, adding whatever data it encounter in to total.
Hope that makes some sense, thanks in a开发者_StackOverflow社区dvance :)
If you want to dereference a pointer you need to use ->
, not .
e.g. your code becomes:
while(currentPtr != NULL)
{
total += currentPtr->getData();
currentPtr = currentPtr->getNextPtr();
}
I also find it more natural to write while(currentPtr)
(i.e. 'while I have a valid pointer') instead of explicitly testing for NULL
.
First of all, you should use ->
instead of .
Second, your code has a minor bug. If you reach the last node, it's next
is NULL
, but that node still has data which you are ignoring. (Because you don't go in the while if ptr->next == NULL
. That said, you should change the condition to ptr != NULL
)
I suggest one of these codes:
If you have a dummy node in the beginning of the list (dummy node is a node with no data, just in the beginning of the list)
int LinkedList::getTotal()
{
int total = 0;
Node *currentPtr = headPtr->getNextPrt();
while (currentPtr != NULL) // or simply while (currentPtr)
{
total += currentPtr->getData();
currentPtr = currentPtr->getNextPtr();
}
return total;
}
And if you don't have a dummy node, it's just a little different:
int LinkedList::getTotal()
{
int total = 0;
Node *currentPtr = headPtr;
while (currentPtr != NULL) // or simply while (currentPtr)
{
total += currentPtr->getData();
currentPtr = currentPtr->getNextPtr();
}
return total;
}
currentPtr
is a pointer, not a class type (object). Use the ->
to access it's members, not .
.
while (currentPrt->getNextPtr()) { ...
The code Node *currentPtr...
declares a pointer to Node.
When accessing member variables or functions of objects through a pointer -
as is the case here - you need to dereference the pointer.
In your case, this means replacing the .
member accessor with a ->
So your code should look like:
while(currentPtr->getNextPtr() != NULL)
{
total += currentPtr->getData();
currentPtr = currentPtr->getNextPtr();
}
精彩评论