I am currently working on a program that takes items from a list recursively and uses them. My problem now is: After the recursive call, the item is added back to the list. My codes looks about as follows (except there ist other stuff going on but that doesnt matter):
public void doStuff(list) {
x, y = someIndices;
elem1 = list[x];
elem2 = list[y];
list.remove(elem1);
doStuff(list);
list.add(elem1);
list.remove(elem2);
doStuff(list);
list.add(elem2);
}
Now if i try to implement that iteratively, I have something like
public void doStuffIteratively(list) {
stack = Stack();
while(!stack.isEmpty()) {
currentList = stack.pop();
list.remove(elem1);
stack.push(list);
...
}
}
In the recursive call I would now add elem1 back to the list but as the "recursive call" here is delayed, there is no real point at which one could add elem1 back to the list. Is there any elegant solution to this?
(One could of course just copy the list and remove the element in the copy but that leads to massive ram usage and is not efficient)