method 1 by using stack