Once we’ve added nodes to a stack, we have the option to inspect the one on the top of the stack! As with the dishes example, you can only see the one at the top. We will be implementing this same functionality by creating a
peek() method. The method will return the top of the stack if it exists. Some things to keep in mind as we build out this method:
- To implement
peek, we will want to use our
LinkedListclass to look at the
headvalue of the linked list. This has to be done with a little care because if the
Stackis empty, this value will be
nil, and we do not want to attempt to return
nil. This will cause a crash!
- Unlike the
peek()method does not alter the Stack.
Add a function to the
Stack with the function signature:
func peek() -> String?.
In the method, add a guard statement to verify the list’s head is not nil. Optional values can come to the rescue here and we can use optional unwrapping to store the safe unwrapped value in a variable called
On the next line, return the node’s
Now that we have implemented a reliable
peek() method, let’s test it out.
Remove your check for
isEmpty() and replace it with a print statement that dynamically outputs:
Top dish: [head_plate_name]
head_plate_name is replaced with the real value for the head.