Oct 17 2019

Nodes in Data Structures – TypeScript

Learn how to implement a simple Node data structure using TypeScript. The first in a series of post about implementing data structures using TypeScript.

nodes-feature-image.png

This is going to be the first in a series of articles covering the various concepts in data structures and their implementation in TypeScript.

Data Structures are an integral part of software development. Having a solid foundation in data structures will allow you to pick the right tool for the job as some structures are better suited for some use cases than others.

The Node is one of the most fundamental data structures in the sense that it is the building block for many other ones and that is why we’ll be looking at it first.

A Node put simply, is a data structure that contains some kind of data, and a pointer (or link) to another Node. Think of it as a small box with two compartments. One compartment holds the content and the next compartment holds a reference to another box just like it.

node-representation A visual representation of a Node

When a Node is being used in another data structure, the other box being linked to is usually (but not always) the very next Node in the structure.

There are some cases where a Node can hold two links to other Nodes, i.e, the previous Node that came before it, and the next Node after it. To keep it simple though, we’re going to limit it to just one link (the next Node) for now.

How would you store the following todo list using only Nodes?

  • Watch Netflix
  • Hit the gym
  • Cook dinner
  • Since the list is in a sequence, we could create three Nodes, and store each of the items in the Nodes as the data.

    And then to link them together, we’d start with the first Node which contains the first item (Watch Netflix) and set its link to point to Node 2 (Hit the gym), and then set Node 2’s link to point to Node 3.

    It would look something like this: node-list A visual representation of a Node list

    We have the theory down so it’s time to implement it. We’ll create a Node class using TypeScript following these constraints:

  • A Node can hold a data
  • A Node can point to another Node
  • A Node’s data can be accessed and updated
  • A Node’s pointer can be accessed and updated
  • First, we’ll create a simple class with a constructor that takes in the data to hold. By default, this Node’s pointer will be set to null.

    We’ll then add some methods to this class to enable us to access the data and update it.

    Time for the pointer. We want to be able to set the pointer to another Node and also to retrieve the Node from the pointer.

    And that’s basically it. As I said, Nodes are really simple but they provide the foundation for more complex data structures like Queues, Linked Lists, etc.

    Next, we’ll be looking at how to implement a Linked List using this Node class we created.

    Goodbye and Happy Coding 🙂