1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

C++ recursion

Discussion in 'C++' started by h994422, Jan 15, 2011.

  1. h994422

    h994422 New Member

    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);
    }
     
    Last edited by a moderator: Jan 16, 2011
  2. h994422

    h994422 New Member

    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);
    }
     
    Last edited by a moderator: Jan 16, 2011
  3. h994422

    h994422 New Member

    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);
    	}
    }
     
    Last edited by a moderator: Jan 16, 2011

Share This Page