devxlogo

Linked Lists and Recursion

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;}

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist