flatten using tail recursion with stack insteead of list concat