Lists: Using Stacks for Word Reversal
Lists: Using Stacks for Word Reversal
Writing words backwards can be a great way to write in code, but sometimes it just gets plain confusing. Maybe you're trying to tell your friend "Live star pals," is how you'd describe your friendship, but you end up with, "Evil rats slap," which just sounds like a low-budget sci-fi movie from the 50s.
Maybe it isn't the best cipher, but being able to spell things backwards shows off some of the important things stacks can do for you.
Using a stack, word reversal—and element reversal in general, for that matter—is really easy. Say you have the word smart and you want to talk about trams instead. For reasons.
Starting with "s", push all the letters, in order from right to left, onto the stack so that it looks like this (but, uh…more computer-y):
To turn this into an emordnilap of "smart," all you need to do is pop each element off until the stack's empty.
Boom. your smarts just turned into a streetcar. Or something like that.
Stacks can also turn words into themselves if you're doing something like checking palindromes. Maybe you want to write a palindrome checker on words like
- mom.
- racecar.
- tacocat.
- UFO tofu.
If you push on the whole word, pop it off again, and none of the words are out-of-order, you know you've got a palindrome on your hands.
Here's what it'll look like in a stack.
Because of the way stacks work, popping all those letters off again means putting them in perfectly reversed order. The only way for a word to equal itself before and after being pushed to and popped from a list is if that word spells the exact same thing both backwards and forwards.
Since racecar equals racecar...we know it's a palindrome.
Even outside the world of interesting-but-ultimately-unuseful word games, stacks can also be useful for other computer science-y things, like…keeping track of parentheses.
No, seriously. Stacks are great at tracking what belongs to what.