I have done the recursive method and do not know exactly why this implementation of the stack isn't working. Please help! I just don't get how to use the stack for the loop.

The Recursive method:

private void solveRecursive(int i) { // do not descend into this object's child nodes, track back if(i > objects.length || rs.getAvailableCapacity() < 0){ return; } // if not rejected current rucksack is best rucksack if(rs.getTotalValue() > maxValue){ maxValue = rs.getTotalValue(); bestRuck.copyFrom(rs); } // we add the object only if its weight is <= available capacity if(i < objects.length && objects[i].getWeight() <= rs.getAvailableCapacity()){ rs.putObject(objects[i]); solveRecursive(i+1); // we remove it so that we can recurse the function without it rs.removeObject(objects[i]); } // recurse the function without object i solveRecursive(i+1); }

The incorrect iterative using stack method:

public void solveIterative() { // A stack to use with the algorithm Deque<Integer> stack = new LinkedList<Integer>(); // The current position in the array of objects int i = 0; stack.push(i); while(!stack.isEmpty()){ int j = stack.pop(); if(j > objects.length || rs.getAvailableCapacity() < 0){ return; } if(rs.getTotalValue() > maxValue){ maxValue = rs.getTotalValue(); bestRuck.copyFrom(rs); } // to add the object if(j < objects.length && objects[j].getWeight() <= rs.getAvailableCapacity()){ rs.putObject(objects[j]); stack.push(j+1); } else{ if(j < objects.length){ rs.removeObject(objects[j-1]); j--; } } } }

Any help would be Greatly appreciated!!!

Thanks!!!