Algorithm For Stack Operations In Java