Now that we have items on our stack, and we know how to
peek at the one on the top, we need to implement the removal of the topmost item off the stack. We’ll call this method,
As shown in the previous exercises, we need to operate on the
LinkedList to return the
head of the stack. We’ll leverage a
removeHead() method in our code from the
LinkedList class to achieve this.
Let’s get started!
In this step, we’ll build out the entire
Add a function to the Stack structure named
pop()that returns an optional String. Note that similar to
push()you should declare it as mutating since we are modifying the stack.
Use the Swift
guardstatement that checks if calling the
listreturns nil. Add a print statement saying
Nothing left to remove!if it does. On the following line, return nil.
Outside of the
guardstatement make sure to print the node’s data that was removed. And finally, return that data.
Now, let’s put all these methods into action together. After the
Top dish: print statement, add four calls to
pop(). Run your code. You should see your dishes moving off the stack in the reverse order they were placed on it. Because we add 3 but remove 4 we should see the
Nothing left to remove! print statement as well.
Note that we are calling
pop() but not using the result which will result in a compiler warning. You can add the code
_ = before the calls to
pop() to avoid this warning.
Give it a try!