Create a Linked List in TypeScript

Paul McBride
InstructorPaul McBride
Share this video with your friends

Social Share Links

Send Tweet

In this lesson we'll cover the basic elements of a linked list and how to append nodes to one.

[00:01] To get started, we'll create the Node class. Each node can be thought of as one of the links in our linked list. It has two properties. The first property is value. This is the data that the node holds. The second property is 'next'. This is a reference to the next Node in our linked list. We also need a [00:21] constructor. The constructor takes one argument, 'value' of type 'any', and it assigns it to this dot value. We also assign null to this dot next. Now, let's create the LinkedList itself. [00:43] You'll notice that I'm exporting it here. We'll use that later for some tests. The linked list has a single property, head. This is of type node or null. It's basically the first element in our linked list. We also need a constructor. [01:03] You can see we just set the property of head to null. Next, let's create the insert method. It takes one argument value of type any. Then, we create a new node by passing that value to it. [01:26] If our linked list is empty, I e, it doesn't have a head, then this step is simple. We take our new Node, and we assign it to head. If that's not the case, we have a little more work to do. We need to find the last element in the list. For that, we'll use a while loop. [01:48] Here, we find the last node in the list by iterating over each node until we find one that doesn't have a 'next' property. Then, we take our new node and assign it to the next property of our current node. The next step is to define a 'ToArray' method. This isn't strictly necessary for a linked list, but it'll help us with testing. [02:15] We'll start by creating an empty array to hold our values. Next, we get the head of the list. Next, we use a while loop to iterate through each element in our [02:35] list. We push its value to the array, and then, finally, we return that array. Now that we have that in place, we should be able to run our first test. The first test we'll look at is this 'can be appended to'. It inserts 2 elements into a new linked list, then we convert it to an array and check we get the results we expect. [02:57] As you can see we still have a few failing tests, but if I scroll up to the first one we can see that it's now passing.