Any reason to do this iteratively? A recursive version would be shorter and easier to read, without the arbitrary stack sizes.