DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Reversing a linked list using Recursion (http://www.daniweb.com/forums/thread122486.html)

Roofus May 5th, 2008 3:43 am
Reversing a linked list using Recursion
 
Hi guys,
I was wondering if I could get some help on the topic of recurrsion. A week ago i was told to create a application using nodes. this week I need to convert the reverse_list fuction I made below into using recursion. any help would be great thanks.

not using recurrsion and works!

void reverse_list (node*& head_ptr)
{       
node* temp_ptr = head_ptr->link();        // holding 2nd node reference.
node* iter_ptr = temp_ptr->link();              // hold the reference of 3rd Node OR NULL.
head_ptr->set_link(0);                // setting the first Node next = 0
while (temp_ptr==NULL)                // looping through 2nd node to the end.
                {
            iter_ptr = temp_ptr->link();                // saving the 3rd Node.
            temp_ptr->set_link(head_ptr);        // reversing
            head_ptr = temp_ptr;                // incrementing head.
            temp_ptr = iter_ptr;                // increment
        }
}
trying to use recurrsion and does not work
void reverse_list (node*& head_ptr)

node* current_ptr = head_ptr->link();                        //holding 2nd node
while (current_ptr->link() != NULL)                //checking if at end of list
        {
        current_ptr->set_link(head_ptr);                        //reversing
        head_ptr = current_ptr;                //incrementing
        reverse_list(head_ptr);                        //calling function again
        }
}

Roofus May 12th, 2008 7:41 pm
Re: Reversing a linked list using Recursion
 
I was able to figure out another way to reverse the linked list using recursion.
        node* reverse_list (node* head_ptr)
        { 
                node* current = NULL;                                               
                if (head_ptr->link() != NULL)                               
                        {
                                current = reverse_list(head_ptr->link());       
                                (head_ptr->link())->set_link(head_ptr);               
                                head_ptr->set_link(NULL);                                       
                        }
                else
                        {
                                current = head_ptr;
                        }
        return current;
        }


All times are GMT -4. The time now is 10:15 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC