These are the solutions to the exercises found in the section, Exercises . The solutions provided here are in Ruby, but you can find the solutions in JavaScript and Python in the code download. [9]
-
Presumably, we’d want to be nice to the callers and answer their phone calls in the order in which they were received. For this, we’d use a queue, which processes data FIFO (First In, First Out).
-
We’d be able to read the 4, which is now the top element in the stack. This is because we’ll have popped the 6 and the 5, which were previously sitting on top of the 4.
-
We’d be able to read the 3, which is now at the front of the queue, after having dequeued the 1 and the 2.
-
We can take advantage of the stack because of the fact that we pop each item in the reverse order of which they were pushed onto the stack. So, we’ll first push each character of the string onto the stack. Then, we’ll pop each one off while adding them to the end of a new string:
<table><tbody><tr><td> <span> </span></td><td> <strong>def</strong> <strong>reverse</strong> (string)</td></tr><tr><td> <span> </span></td><td>stack = Stack. <strong>new</strong> </td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td>string. <strong>each_char</strong> <strong>do</strong> |char|</td></tr><tr><td> <span> </span></td><td>stack. <strong>push</strong> (char)</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td>new_string = <em>""</em> </td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <strong>while</strong> stack. <strong>read</strong> </td></tr><tr><td> <span> </span></td><td>new_string += stack. <strong>pop</strong> </td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <strong>return</strong> new_string</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr></tbody></table>