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

The Graph, GraphNode, and GraphEdge structures are almost complete! The last piece to the current Graph implementation is the ability to remove nodes.

Removing a node in a graph is a bit more complex as compared to removing one from a tree. We’ll need to:

  • Remove it from the nodes array
  • Remove any edges that contain the node from the edges array
  • Remove the node from any other nodes’s neighboringNodes array.

Instructions

1.

Get started by creating a new Graph method removeNode(_:) with an omitted argument label and an internal parameter node of type GraphNode.

2.

Inside removeNode(_:), create an if let constant index equal to the first index inside nodes that matches the node to remove. If a node is found, remove the node from the nodes array using the Array.remove(at:) method.

3.

After the if let statement, assign edges to edges filtered where GraphEdge.nodeOne or GraphEdge.nodeTwo is not equal to the node to remove.

4.

As a final step, we’ll need to remove the node as a neighbor from each node in the nodes array. Use a forEach on nodes and call removeNeighbor(node) on each element using shorthand argument syntax.

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?