Insert values into a TypeScript Linked List with insertAt

Paul McBride
InstructorPaul McBride
Share this video with your friends

Social Share Links

Send Tweet
Published 5 months ago
Updated a month ago

We'll learn to how add a new elements to a linked list at a specific index.

[00:00] Next, let's create the 'insert at' method. This method takes 2 arguments: index, which is the index we want to insert our new Node, and value, that's the data our new node will hold. Next, we create that node. Just [00:20] like before, we pass the value to that new node. If we pass an index of 0, that means we're trying to set our new node as the head of the list. We do that by taking the current head of the list and assigning that to the next property of our node, then we [00:40] assign our Node as the current head of the list. If we pass an index of anything other than 0, we first need to find the Node at that index. We'll iterate through each Node using a for loop. [01:02] You can see here the TypeScript is giving us an error. Current is possibly null. Let's fix that. This will happen if the user passes an index that's out of bounds. Now that we have the current node, let's figure out how to insert the new [01:22] one. We start by taking the next attribute of the current node and we assign that to the next attribute of our new node. Then, we assign our node to the next attribute of the current node. You'll see here TypeScript is [01:41] giving us another error it's the same thing as before. We should now be ready for our next test. This test is pretty similar to the first. We create a new linked list, we insert 3 new nodes, and [02:01] then we insert the number 4 at the index of 1. Finally, we call toArray and we check that we get the results we're expecting. Just like before, we still have a few failing tests. But if we scroll up, we should now see that we have 2 tests passing.

egghead
egghead
~ an hour ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today