I’m reading The C Programming Language and learned how to make a reverse Polish calculator using a stack. Here is one of the exercises that follow it:
Exercise 4-4. Add the commands to print the top elements of the stack without popping, to duplicate it, and to swap the top two elements. Add a command to clear the stack.
What do they mean by ‘duplicate’? Does it mean to print out the entire stack, or to push the entire stack onto itself (so that, for example, ‘1 2 3’ would become ‘1 2 3 1 2 3’), or what?
No, it makes more sense to duplicate an individual element on the top of the stack. I suspect "print the top elements" was a typo that should have been the singular "print the top element".
The reason this is a far more likely case is because printing the "top elements" makes no sense on its own. If it was some subset of the stack other than just the top element, it would require a count to be specified (and it doesn’t) or, if it meant them all, it would not need the "top" qualifier at all.
That means the subject "it", in this case, refers to "the top element of the stack", not "the stack".
So if your stack is:
with
1being the first element pushed and5the last, duplicating would give you:Assuming you have the basic operations
pushandpopalready, you probably need to addcountandpeekwhich will give you, respectively, the current element count and the top element of the stack (basically apopbut without removing it).The rest of the code could then be built from those basic operations (pseudo-code), something like:
That’s probably the simplest way to implement them, though there may be efficiency gains if you write the functions assuming you have more power than just calling the basic operations. For example, you could
swapTopTwojust by swapping the two elements in-place rather than popping and pushing (variables starting with_are internal to the implementation in the following):