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

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.