implemented toList using tail recursion.