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

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS