rewrite by the algorithm using stack