Stacks operate by making modifications just to the top, or head, of the stack. If we want to add a plate to our dish stack, we add it to the top of the pile. To add an item to the stack, we will use the
.push() method. Our
.push() method will:
- Add an item to the stack.
- Print a statement that notifies the user of the changes to the stack.
Keep in mind that our stack is an instance of a
LinkedList which is built using the
Node class, thus we can rely on their properties and methods to help us in our implementation.
Add a function to the
Stack structure with the function signature
func push(_ str: String). Note that you should declare it as
mutating since we are modifying the values of our properties within the
push() function, use the
addToHead() method of the
LinkedList class to add the
str variable onto the stack.
Next, print out the string,
Now, let’s make some dirty dishes! We have already created a Stack called
dishes and display that it is empty with a print statement.
Let’s add three dishes, one called
"blue plate" another called
"white plate", and a final one called
Finally, print out the value of the computed property
isEmpty again to show the values that have been added. It should now return