Log in from a computer to take this course

You'll need to log in from a computer to start Introduction to Non-linear Data Structures in Swift. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
Learn

Now that we can add a task to our heap and we can see that our heapifyUp() function is working as advertised, it is time to start getting access to the items we add to our To-Do List so we can get things done!

The first access function we are going to create is getTask() which will work the same as a peek() function. It would be a pain if every time we accessed the heap we had to remove the top item to work on it and then put it back into the heap if we didn’t finish it. Besides making our code base less readable, it also eats up processing power every time we have to reorganize the heap.

Our getTask() will give the user access to the task on top of the heap without actually removing the TaskNode from the heap. To execute this process first we check if the heap has items and if it does, we read the top task and present it to the user so they can begin work. Since we are storing our heap in an array, the top of the heap is located at index 0.

Instructions

1.

Under the getTask comments in the MinHeap class, create a new function, getTask() that has no parameters and returns nothing. Leave the function body empty.

2.

Inside the function create an if statement that checks if the heap has any elements in it. If it doesn’t, print Your task list is empty, good job!. At the bottom of the file, add a call to getTask() after toDoList has been instantiated, but before any tasks have been added.

3.

Add an else clause to print the next task to the user by accessing the first element of the heap. It should print “Your next task is: “ followed by the element. There are many ways to do this, as long as the output has the exact text specified, you can complete this instruction as you see fit.

After the tasks have been added to toDoList, make another call to getTask() and see your results.

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?