Fixed memory leak in `while' method

`while' method used O(n) extra memory. New one uses O(1).