Delete a Linked List Node at a given Index in TypeScript

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 how to remove a Node from a Linked List at a given Index.

[00:00] Let's implement the delete method next. Delete takes one argument index and it will delete the node at that index. We'll start by handling the case where the index is 0. Here, we're assigning the next property of the current head of the list to head if it [00:20] exists. Otherwise, we assign null. Then we return early. If the index is anything other than 0, we still have some work to do. Just like the insert method, we need to find the node at the index provided. The code will look pretty similar. [00:41] We'll use a for loop to iterate through each node checking for out of bounds errors to find the node we're looking for. After the loop, we need to [01:01] check the current exists and current's next property. Finally, let's remove the node. We do that by assigning current.next.next to current.next. [01:21] That essentially removes current.next from the list. Let's check our tests and make sure it worked. Again, similar kind of test, we create a new linked list, we insert 3 elements and then we try and delete 1. Finally, we check to see if we've got the results we want. [01:41] Once again we scroll up and you can see we now have 3 passing tests.

egghead
egghead
~ 4 minutes 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