Permuting a String Using a Stack

The following algorithm is taken from


Push the string +meat on the stack.
While the stack is not empty
Pop off the top of the stack.
If that string ends in a + (such as tame+)
Remove the + and add the string to the list of permutations.
Remove each letter in turn from the right of the +.
Insert it just before the +.
Push the resulting string on the stack.

For example, after popping e+mta, you push em+ta, et+ma, and ea+mt