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 LinkedList class to look at the head value of the linked list. This has to be done with a little care because if the Stack is empty, this value will be nil, and we do not want to attempt to return nil. This will cause a crash!
  • Unlike the push() method, 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 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.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?