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

Cyclic graphs are graphs that contain at least one cycle. This means that as you traverse the graph, somewhere in the graph, it is possible to leave a node and return to that same node through the cycle.

Consider the following sequence of events for learning how to ride a bike:

  • You get on the bike
  • You begin pedaling the bike
  • You fall down
  • You get back on the bike

The cycle of getting on the bike, pedaling, and falling off will happen until you have successfully mastered riding a bicycle. There is no restraint on how many times this could take, and happens a lot when you’re learning!

Let’s create the cyclic graph above using Swift.

Instructions

1.

Create a node for the following events: “Get on Bike”, “Pedal Bike”, “Fall off Bike”,

Name these nodes getOn, pedal, and fall respectively.

2.

Create a constant graph of type Graph with the nodes above.

3.

Lastly, we’ll combine the nodes using addEdge(from:to:) for each pair of nodes:

  • "Get on Bike" -> "Pedal"
  • "Pedal" -> "Fall"
  • "Fall" -> "Get on Bike"
4.

Print the graph using the printGraph() function.

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?