Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am having trouble with link lists and recursion I was hoping someone can guide through this question:

suppose that the class LinkedBag did not have the data member item_count_. Revise the method getCurrentSize so that it counts the number of nodes in the linked chain a. iterartively b. Recursively

The original GetCurrentSize() is just
int LinkedBag<ItemType>::GetCurrentSize() const
{
  return item_count_;
}  

Here is what I have so far:
C++
int GetCurrentSize(node* p)
{
        if (p==NULL)
                return 0;
        else{
             return 1 + GetCurrentSize(cur->next_node);
             }

}

C++
int GetCurrentSize(node* cur){
    int count;
    while(cur != NULL){     
        cur->next_node;
        count++
        }
return count;

}
Posted
Updated 2-Mar-15 11:41am
v5

Besides the fact that the compile has no way to know which version of GetCurrentSize you intend to use at any point, because they have the same signature. Your iterative version declares the count from within the loop, so it's value is not necessarily carried from iteration to iteration. It fails to initialize it at all. And you never actually return the value.
More like:
C++
int GetCurrentSize(node* cur){
        int count = 0;
    while(cur != NULL){
        cur->next_node;
        count++
        }
    return count;
}
 
Share this answer
 
for recursion you first need to make the base case e.g

C#
if(cur==NULL) return 0;

then in other cases:

C#
else{
return 1 + GetCurrentSize(cur->next_node);
}
 
Share this answer
 
Is it correct now?
XML
<pre lang="c++">
int GetCurrentSize(node* p)
{
        if (p==NULL)
                return 0;
        else{
             return 1 + GetCurrentSize(cur-&gt;next_node);
             }

}
</pre>
<pre lang="c++">
int GetCurrentSize(node* cur){
    int count;
    while(cur != NULL){
        cur-&gt;next_node;
        count++
        }
return count;

}
</pre>
 
Share this answer
 
Comments
PIEBALDconsult 2-Mar-15 17:48pm    
Please use Improve question to update the question, do not post it as a solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900