C++ recursion

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

  1. h994422

    h994422 New Member

    Joined:
    Sep 13, 2010
    Messages:
    14
    Likes Received:
    0
    Trophy Points:
    0
    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

    Joined:
    Sep 13, 2010
    Messages:
    14
    Likes Received:
    0
    Trophy Points:
    0
    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

    Joined:
    Sep 13, 2010
    Messages:
    14
    Likes Received:
    0
    Trophy Points:
    0
    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

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice