remove recursion, use stack to keep track of the loops