convert Recursion to linear can it be done

This is a discussion on convert Recursion to linear can it be done within the C++ Programming forums, part of the General Programming Boards category; Hello all i have legacy code that preform Recursion calling this Recursion is very heavy and long and sometimes it ...

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    58

    convert Recursion to linear can it be done

    Hello all
    i have legacy code that preform Recursion calling this Recursion is very heavy and long and sometimes it gives me stack overflow exceptions
    i wander in general or algorithmic view can i convert Recursion flow to linear ( not Recursion) ?
    Thanks

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Depends on your algorithm I guess. You could try to implement a normal loop and using a std::stack to keep whatever state you have (instead of performing the resursive call).

    Something like this (semi-pseudo code):
    Code:
    std::stack<MyState> Stack;
    Stack.push(InitialState);
    
    while(Stack.length > 0)
    {
      CurrentState = Stack.pop();
      //Do something with current state, if recursion is needed call Stack.push(SubState);
    }
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Registered User
    Join Date
    Mar 2008
    Posts
    58
    hello and thanks for the reply but i didnt understand this
    how can i save state ?
    and how can i convert it to my flow .
    can you explain me on the classic factorial function
    thanks allot

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Template Recursion Pickle
    By SevenThunders in forum C++ Programming
    Replies: 20
    Last Post: 02-05-2009, 09:45 PM
  2. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 06:20 AM
  3. convert string into integer using recursion
    By peter_hii in forum C++ Programming
    Replies: 18
    Last Post: 08-23-2006, 11:09 AM
  4. Convert Char to Int Function
    By drdroid in forum C++ Programming
    Replies: 9
    Last Post: 02-19-2003, 12:53 PM
  5. a simple recursion question
    By tetra in forum C++ Programming
    Replies: 6
    Last Post: 10-27-2002, 10:56 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21