Learn

Our Stack implementation is now complete. We can push, pop, and peek values on the Stack. As we know if we attempt too many pops eventually nil is returned as there are no Nodes on the stack.

However, what happens if we keep adding nodes onto the Stack? There is nothing limiting the size of the stack! As we know with dishes, if the pile of dishes gets too high we may have a crash! This is the same for us, Stacks take up memory and in many cases, we will want a limit on the size.

In this exercise, we will extend our Stack class to have the concept of maximum size.

Instructions

1.

We need to set the maximum size of the Stack.

First, let’s create a private var property called size in our Stack struct and set the initial value to 0.

Next, we will add private var property called maxSize which we will initialize in the init() function. Set the type of this to be Int.

With structs, all properties need to be initialized inline where the property is declared as size was or we need to initialize it in the init() function.

Create an initializer and pass in a maxSize parameter of type Int.

For our exercise let’s set the default value to 2.

Initializers have the format init(<variable name>:<type> = <default value>)

Be sure to save the maxSize parameter into the maxSize property.

2.

Now that we have size and maxSize properties we can add these into push() and pop().

In push() add a guard statement in the first line of the method to check that size < maxSize. If the else is invoked we want to print out The stack is full! No room to add \(str) and return.

If we do not enter the else, we know we will be adding on to the stack. In this case, increment the size property by 1 before we call addToHead().

In pop() we already have a guard statement allowing us confidence that there is a node that has been removed. We simply need to add a decrement of size by 1 before we return node.data.

Give it a try! In this case our defensive code should only allow two plates on the stack!

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?