Reversing a linked list using Recursion

Reply

Join Date: May 2008
Posts: 5
Reputation: Roofus is an unknown quantity at this point 
Solved Threads: 0
Roofus Roofus is offline Offline
Newbie Poster

Reversing a linked list using Recursion

 
0
  #1
May 5th, 2008
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!

  1. void reverse_list (node*& head_ptr)
  2. {
  3. node* temp_ptr = head_ptr->link(); // holding 2nd node reference.
  4. node* iter_ptr = temp_ptr->link(); // hold the reference of 3rd Node OR NULL.
  5. head_ptr->set_link(0); // setting the first Node next = 0
  6. while (temp_ptr==NULL) // looping through 2nd node to the end.
  7. {
  8. iter_ptr = temp_ptr->link(); // saving the 3rd Node.
  9. temp_ptr->set_link(head_ptr); // reversing
  10. head_ptr = temp_ptr; // incrementing head.
  11. temp_ptr = iter_ptr; // increment
  12. }
  13. }
trying to use recurrsion and does not work
  1. void reverse_list (node*& head_ptr)
  2. {
  3. node* current_ptr = head_ptr->link(); //holding 2nd node
  4. while (current_ptr->link() != NULL) //checking if at end of list
  5. {
  6. current_ptr->set_link(head_ptr); //reversing
  7. head_ptr = current_ptr; //incrementing
  8. reverse_list(head_ptr); //calling function again
  9. }
  10. }
Reply With Quote Quick reply to this message  
Join Date: May 2008
Posts: 5
Reputation: Roofus is an unknown quantity at this point 
Solved Threads: 0
Roofus Roofus is offline Offline
Newbie Poster

Re: Reversing a linked list using Recursion

 
0
  #2
May 12th, 2008
I was able to figure out another way to reverse the linked list using recursion.
  1. node* reverse_list (node* head_ptr)
  2. {
  3. node* current = NULL;
  4. if (head_ptr->link() != NULL)
  5. {
  6. current = reverse_list(head_ptr->link());
  7. (head_ptr->link())->set_link(head_ptr);
  8. head_ptr->set_link(NULL);
  9. }
  10. else
  11. {
  12. current = head_ptr;
  13. }
  14. return current;
  15. }
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the C++ Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC