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 ourLinkedList
class to look at thehead
value of the linked list. This has to be done with a little care because if theStack
is empty, this value will benil
, and we do not want to attempt to returnnil
. This will cause a crash! - Unlike the
push()
method, thepeek()
method does not alter the Stack.
Instructions
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 node
.
On the next line, return the node’s data
value.
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]
where head_plate_name
is replaced with the real value for the head.