Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   C++ recursion (http://www.go4expert.com/forums/cpp-recursion-t24553/)

h994422 16Jan2011 02:30

C++ recursion
 
Hi.I have to convert a function to recursive type.It insert a new integer to the array based linked list.My recursion does not work properly. Need help. Thanks.

Function:
Code:

void ListRecursive::insert ( int index , ListItemType newItem , bool& success )
{
if((index>=1) && (index<=size+1) && (size<MAX_SIZE))
        {
                for(int pos=size ; pos>=index ; --pos)
                        items[translate(pos+1)]=items[translate(pos)];
                //insert new item
                items[translate(index)]=newItem;
                ++size;        //increase the size of the list by one
        }
}

Recursive Type:
void ListRecursive::insert ( int index , ListItemType newItem , bool& success )
{
        int pos=size;
        if(pos==index)
                items[index]=newItem;
        else
                return insert(index-1, newItem , success);
}


h994422 16Jan2011 02:47

Re: C++ recursion
 
a newer version.Works on an empty list. But still doesn't work on non-empty lists.

Code:

void ListRecursive::insert ( int index , ListItemType newItem , bool& success )
       
{
        if(size==index-1)
        {       
                items[size]=newItem;
                ++size;
        }
        else
                return insert(index-1, newItem , success);
}


h994422 16Jan2011 02:59

Re: C++ recursion
 
finally..!
is there any problem with this code? i think i made it..!
Code:

void ListRecursive::insert ( int index , ListItemType newItem , bool& success )
       
{
        if(size==index-1)
               
                items[size++]=newItem;
        }
        else
        {
                items[size]=items[size-1];
                --size;
                return insert(index, newItem , success);
        }
}



All times are GMT +5.5. The time now is 15:15.