Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Algorithms
Expertise: Beginner
Aug 12, 1999

Linked Lists and Recursion

Question:
I am using several large data structures as linked lists to process some data. Many of my helper functions use recursion. Because of the size/amount of data that I'm handling, the recursion has become bulky and uses up all of the memory on my system.

How can I rewrite this addnode function as interative rather than recursive?

 
struct node {
  int data;
  node* next;
};

node* addnode (node* addtothis, int n) {
  if (addtothis==NULL) {
    node* temp=new node;
    temp->data=n;
    temp->next=NULL;
  }
  else {
    addtothis->next=addnode(addtothis
                           ->next, n);
  }
  return addtothis;
}
This is not the actual code I'm using, but the answer would help me rewrite it.

Answer:
You can do some cool things with recursion but if the algorithm has the potential of going too deep, you can blow the stack. This is in addition to slowing down due to the overhead of the recursive call.

When a recursive function calls itself toward the end, it is said to be "tail recursive." A tail-recursive routine is normally easy to convert to a non-recursive loop. You simply update any variables that reflect the current state and loop.

I suspect that you would probably rework your code a little more to make it non-recursive. For example, you might require that the addtothis argument is non-NULL, otherwise there is nothing to add to.

Here's my change to get you started. Please note that I had no easy way to test this so it is untested just as I typed it:

 
void addnode (node* addtothis, int n)
{
  node *pTemp = NULL;

  while (addtothis != NULL) {
    pTemp = addtothis;
    addtothis = addtothis->next;
  }
  node* temp=new node;
  temp->data=n;
  temp->next=NULL;
  if (pTemp != NULL)
    pTemp->next = temp;
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date