Linked List - Beau teaches JavaScript

**Introduction to Linked Lists**

A linked list is a data structure that consists of nodes, where each node contains a value and a reference (or "link") to the next node in the sequence. This allows for efficient insertion and deletion of elements at any position in the list. In this article, we will explore how to implement a linked list in Python, including methods for adding, removing, and accessing elements.

**Adding Elements to a Linked List**

To add an element to the end of the linked list, we create a new node with the given value and set its next pointer to the current tail of the list. We then update the tail pointer to point to the new node. This process can be repeated to add elements in the middle of the list.

Here is an example implementation:

```python

class Node:

def __init__(self, value):

self.value = value

self.next = None

class LinkedList:

def __init__(self):

self.head = None

self.tail = None

self.length = 0

def add(self, value):

new_node = Node(value)

if not self.head:

self.head = new_node

self.tail = new_node

else:

self.tail.next = new_node

self.tail = new_node

self.length += 1

def __str__(self):

values = []

current = self.head

while current:

values.append(str(current.value))

current = current.next

return ' -> '.join(values)

```

**Accessing Elements in a Linked List**

To access an element at a specific index, we need to traverse the list until we reach that index. We can do this using a simple while loop.

Here is an example implementation:

```python

def get_element_at_index(self, index):

if index < 0 or index >= self.length:

return None

current = self.head

for _ in range(index):

current = current.next

return current.value

# Example usage:

ll = LinkedList()

ll.add(1)

ll.add(2)

ll.add(3)

print(ll.get_element_at_index(0)) # Output: 1

print(ll.get_element_at_index(1)) # Output: 2

print(ll.get_element_at_index(2)) # Output: 3

```

**Removing Elements from a Linked List**

To remove an element at a specific index, we need to find the node before that index and update its next pointer. We also need to decrement the length of the list.

Here is an example implementation:

```python

def remove_at_index(self, index):

if index < 0 or index >= self.length:

return None

if index == 0:

self.head = self.head.next

else:

current = self.head

for _ in range(index - 1):

current = current.next

current.next = current.next.next

self.length -= 1

return current.value

# Example usage:

ll = LinkedList()

ll.add(1)

ll.add(2)

ll.add(3)

print(ll.remove_at_index(0)) # Output: 2

print(ll) # Output: 1 -> 3

```

**Adding at a Specific Index**

To add an element at a specific index, we need to find the node before that index and update its next pointer. We also need to increment the length of the list.

Here is an example implementation:

```python

def insert_at_index(self, value, index):

if index < 0 or index > self.length:

return None

if index == 0:

new_node = Node(value)

new_node.next = self.head

self.head = new_node

self.tail = new_node

else:

current = self.head

for _ in range(index - 1):

current = current.next

new_node = Node(value)

new_node.next = current.next

current.next = new_node

self.length += 1

return None

# Example usage:

ll = LinkedList()

ll.add(1)

ll.add(2)

print(ll.insert_at_index(3, 0)) # Output: 3

print(ll) # Output: 3 -> 2

```

**Removing Elements at a Specific Index**

To remove an element at a specific index, we need to find the node before that index and update its next pointer. We also need to decrement the length of the list.

Here is an example implementation:

```python

def delete_at_index(self, value, index):

if index < 0 or index >= self.length:

return None

current = self.head

for _ in range(index):

current = current.next

if current.value == value:

if current == self.tail:

self.head = None

self.tail = None

else:

previous_node = self.head

while previous_node.next != current:

previous_node = previous_node.next

previous_node.next = current.next

self.length -= 1

return None

# Example usage:

ll = LinkedList()

ll.add(1)

ll.add(2)

print(ll.delete_at_index(1, 0)) # Output: None

print(ll) # Output: 2

```

**Conclusion**

In this article, we have explored how to implement a linked list in Python, including methods for adding, removing, and accessing elements. We have also discussed the importance of tail pointers and indices when working with linked lists. With these techniques and data structures, you can build efficient algorithms for solving complex problems in computer science.

"WEBVTTKind: captionsLanguage: ena linked list is a common data structure where elements are stored in a node the node contains two key pieces of information the element itself and the reference to the next node so in this example the element here would be one and then here's the reference to the next note this arrow is pointing to the 2. this 2 is the element we're storing the information 2 and the way this length linking to the next node like arrays linked lists can be used to implement many other data structures linked lists have some advantages and disadvantages when compared to arrays traditionally arrays are just have a fixed size and linked lists have dynamic size so you can just keep adding links and you don't have to do anything differently javascript kind of hides some of this but when you create an array it can only be a fixed size also arrays have pretty inefficient insertions and deletions while linked lists are very efficient insertions and deletions a benefit to arrays are the random access which means you can say you want something at index five and you can instantly get the thing at index five however with linked list if you want something at index five you have to go through every element in the linked list to get to index five and then for raise they may result in much memory waste to make up for the fact that arrays can only only be made at a fixed size sometimes they will be created a lot bigger than what you really need to make sure you have enough room for everything however in a linked list because of the dynamic size there is no wasted memory and then we have really fast sequential access for raise and slow for linked lists so every linked list is going to have a head so we have this head pointer here that points to the the first node and then it's also going to have a size so that's just the amount of node so in this example here the size will be three and you can see each node points to the next node in the last node just points to null because there's no next node so if you look at the code over here we start with the head of null because we don't have a head yet and the length is going to be zero and the linked list is made up of nodes so here's how we're going to create a node we pass in an element and this dot element is set to element this dot next is set to null so this dot element in the picture is the info and this dot next in the picture is the link so it starts off just like the last element where the link is pointing to null next is point to null then we just have a few simple functions this.size just returns the length and this dot head just returns the head and here is the add function whatever you're going to pass into the linked list is going to be the element so you're going to add the element and then we're going to create a new node with that element so after you pass in the element and it creates this new node the element of the node is set to the element you passed in but the next of the node is set to null so if head equals null that means there are no nodes in the linked list yet so we just set the head to equal the node and at that point there would just be one node in the linked list and the head would be pointing that first node else that means there's more than one element in the list we're gonna set the current node to equal the head and let's add a var in front of here so this just means that we're going to start at the the head node which you always have to do whenever you're doing anything to a linked list you start the beginning and then you can go through each item in the list while currentnode.next that means while there is a current.next while currentnode.next does not equal null you can see at the end remember the link equals currentnode.next so at the end it equals null so before the end of the list the current node.next which would be the link does not equal null it equals the next node so this just means while there is a next node current node equals currentnode.next so that's just a way to hop from node to node on the list once there is no current node.next that means we're at the end of the list the end of the list is where we want to add the element that we're adding now we'll set currentnode.next to equal the node once we get to the last node in the list we'll set the current node.next or this link to equal the new node we added instead of null and we just increment the length the remove method takes an element and searches the linked list to find and remove the node containing that element so you're passing the element that you want to remove and we always start at the head current node equals head and then we also need to know the previous node when you're going to remove something so if the current node.element equals element if currentnode.element equals element well that just means that the head node is the element we're trying to remove so if we're trying to remove the head node we just have to set the head to current node.next so the head pointer will be pointing to the next node if the head node is not the node we're looking for we go to the else so else while current node.element does not equal element basically while the node we're on does not equal the node we're searching for previous node is going to equal the current node like i said we have to keep track of the previous node and then the current node is going to equal current node.next which just means we're going to keep going through this while loop and keep jumping to the next node on the list until we find the node we're looking for let's let's say it's the second note on this example here we're going to set previous node.next to equal current node.next if we're trying to remove this second node we're going to set previousnode.next so the previous node.next would he be the first node so that'll be the link the link is now going to not point to the current node the link is going to point to the current node.next we would skip over that node and point to the current node.next right here and that's how a node would be deleted from the linked list and then we just decrement the link now here's another quick function it's empty return length equals equals equals zero so if the length equals zero we're going to return true if it doesn't equal zero we're going to return false and you may want to know the index of a specific element so we're just going to have to hop from node to node until we find that element and then return that index so the current node is going to equal head start at the beginning index is going to start at negative 1 and so while current node that means while there is a current node while it's not null we're going to increment the index so at this point if we start at the beginning we've incremented the index so where the index is now is zero so if current node that element equals element return index so if the first element which would be this info equals what we passed in up here we're going to return the index so if instead of the head node we're going to return the index 0. if not current node equals currentnode.next and we're going to continue doing this while loop and just hop from node to node and then then we're going to eventually be able to return the index as we keep adding one to the index for every time we do the while loop and if we go through the whole while loop and don't find anything we're going to return negative 1. that just means the element is not in the linked list so we just found the index of an element now we're going to find the element at an index that's just the opposite you're passing an index number and you're going to return the element so we have current node equals head count equals zero and here's the while loop here while count is less than index that means we haven't gotten to the index we're searching for increment count and current node equals current node.next so that means we hop to the next node so we're going to keep going through every node in the list until count is not less than index that means count equals index so we've reached the right index so we can just return current node dot element now in it you're going to pass in the index and the element and add remember you always add to the end of the linked list but in add at you can add in the middle of the list so just like add we're going to create a new node with the element we pass in and the current node is going to equal head we always start at the beginning we need to keep track of the previous node and the current index is going to equal 0. so if index is more than length that means we've passed an index that's way bigger than the actual length of the linked list so we cannot add at that index when we return false if index equals zero that means we're trying to add the element to the head node so we'll set node.next or node is a node that we just passed in so the next element is now going to be the current node which would be the current head node and then we just set the head to equal the node that we passed in else we don't want the index to be the head node while current index is less than index we're going to go through each index until we find the correct index so current index increment we're going to set the previous node to equal the current node so we want to keep track of the previous node the current node is going to equal currentnode.next we're going to keep going through this while loop until we find the correct node so if we want to add a node as index 1 or the second node in the list once we get to that index we're going to set node.next equal to current node so our node.next is the node we passed in and we're going to set that to equal the current node which would be this index right here then we have to set previous node.next to equal the node that we're passing in and then we just increment the length and the last function i'm going to talk about is remove it now remove it and add it are very similar a lot of the lines are the same except we're not gonna create a new node the current node's gonna be the head we need a previous node the current index is gonna be zero here is a slightly different thing if the index is less than zero or if the index is more than or equal to length return null so we cannot remove a negative index and we cannot remove an index greater than the length of the list if index equals zero we're trying to remove the head node so we just set the head node to equal the current node.next so instead of the head pointer pointing to this node right here that head pointer is going to point to the next node right here else this part is just like the add at we're just going to keep going through each element on the list and once we find the element we want to remove like let's say we're removing this second element at index one we're going to set previousnode.next to equal current node.next we're going to set the previous node.next or this link is going to point to whatever was in the link to the current node or so this link is going to point to now this node right here and we're going to completely take out this one and then we're going to do length minus minus and return the node that we're removing and now we're just going to quickly show an example of using the linked list we're going to call the linked list conga because a linked list is kind of like a conga line and let me bring up the console so we're going to create this new linked list we're going to add some items kitchen puppy dog cat fish we're going to show the size we're going to remove the third item on the list so we'll run that and see we're going to remove cat now let's copy this we're gonna do element at then we'll try index aft and for the element we're gonna put puppy look i mean index of so we remove cat uh now we check the new element three which is going to be fish and the index of puppy is gonna be one uh kitchen would be zero coffee is one and the size is four well that's the linked list thanks for watching my name is beau carnes don't forget to subscribe and remember use your code for gooda linked list is a common data structure where elements are stored in a node the node contains two key pieces of information the element itself and the reference to the next node so in this example the element here would be one and then here's the reference to the next note this arrow is pointing to the 2. this 2 is the element we're storing the information 2 and the way this length linking to the next node like arrays linked lists can be used to implement many other data structures linked lists have some advantages and disadvantages when compared to arrays traditionally arrays are just have a fixed size and linked lists have dynamic size so you can just keep adding links and you don't have to do anything differently javascript kind of hides some of this but when you create an array it can only be a fixed size also arrays have pretty inefficient insertions and deletions while linked lists are very efficient insertions and deletions a benefit to arrays are the random access which means you can say you want something at index five and you can instantly get the thing at index five however with linked list if you want something at index five you have to go through every element in the linked list to get to index five and then for raise they may result in much memory waste to make up for the fact that arrays can only only be made at a fixed size sometimes they will be created a lot bigger than what you really need to make sure you have enough room for everything however in a linked list because of the dynamic size there is no wasted memory and then we have really fast sequential access for raise and slow for linked lists so every linked list is going to have a head so we have this head pointer here that points to the the first node and then it's also going to have a size so that's just the amount of node so in this example here the size will be three and you can see each node points to the next node in the last node just points to null because there's no next node so if you look at the code over here we start with the head of null because we don't have a head yet and the length is going to be zero and the linked list is made up of nodes so here's how we're going to create a node we pass in an element and this dot element is set to element this dot next is set to null so this dot element in the picture is the info and this dot next in the picture is the link so it starts off just like the last element where the link is pointing to null next is point to null then we just have a few simple functions this.size just returns the length and this dot head just returns the head and here is the add function whatever you're going to pass into the linked list is going to be the element so you're going to add the element and then we're going to create a new node with that element so after you pass in the element and it creates this new node the element of the node is set to the element you passed in but the next of the node is set to null so if head equals null that means there are no nodes in the linked list yet so we just set the head to equal the node and at that point there would just be one node in the linked list and the head would be pointing that first node else that means there's more than one element in the list we're gonna set the current node to equal the head and let's add a var in front of here so this just means that we're going to start at the the head node which you always have to do whenever you're doing anything to a linked list you start the beginning and then you can go through each item in the list while currentnode.next that means while there is a current.next while currentnode.next does not equal null you can see at the end remember the link equals currentnode.next so at the end it equals null so before the end of the list the current node.next which would be the link does not equal null it equals the next node so this just means while there is a next node current node equals currentnode.next so that's just a way to hop from node to node on the list once there is no current node.next that means we're at the end of the list the end of the list is where we want to add the element that we're adding now we'll set currentnode.next to equal the node once we get to the last node in the list we'll set the current node.next or this link to equal the new node we added instead of null and we just increment the length the remove method takes an element and searches the linked list to find and remove the node containing that element so you're passing the element that you want to remove and we always start at the head current node equals head and then we also need to know the previous node when you're going to remove something so if the current node.element equals element if currentnode.element equals element well that just means that the head node is the element we're trying to remove so if we're trying to remove the head node we just have to set the head to current node.next so the head pointer will be pointing to the next node if the head node is not the node we're looking for we go to the else so else while current node.element does not equal element basically while the node we're on does not equal the node we're searching for previous node is going to equal the current node like i said we have to keep track of the previous node and then the current node is going to equal current node.next which just means we're going to keep going through this while loop and keep jumping to the next node on the list until we find the node we're looking for let's let's say it's the second note on this example here we're going to set previous node.next to equal current node.next if we're trying to remove this second node we're going to set previousnode.next so the previous node.next would he be the first node so that'll be the link the link is now going to not point to the current node the link is going to point to the current node.next we would skip over that node and point to the current node.next right here and that's how a node would be deleted from the linked list and then we just decrement the link now here's another quick function it's empty return length equals equals equals zero so if the length equals zero we're going to return true if it doesn't equal zero we're going to return false and you may want to know the index of a specific element so we're just going to have to hop from node to node until we find that element and then return that index so the current node is going to equal head start at the beginning index is going to start at negative 1 and so while current node that means while there is a current node while it's not null we're going to increment the index so at this point if we start at the beginning we've incremented the index so where the index is now is zero so if current node that element equals element return index so if the first element which would be this info equals what we passed in up here we're going to return the index so if instead of the head node we're going to return the index 0. if not current node equals currentnode.next and we're going to continue doing this while loop and just hop from node to node and then then we're going to eventually be able to return the index as we keep adding one to the index for every time we do the while loop and if we go through the whole while loop and don't find anything we're going to return negative 1. that just means the element is not in the linked list so we just found the index of an element now we're going to find the element at an index that's just the opposite you're passing an index number and you're going to return the element so we have current node equals head count equals zero and here's the while loop here while count is less than index that means we haven't gotten to the index we're searching for increment count and current node equals current node.next so that means we hop to the next node so we're going to keep going through every node in the list until count is not less than index that means count equals index so we've reached the right index so we can just return current node dot element now in it you're going to pass in the index and the element and add remember you always add to the end of the linked list but in add at you can add in the middle of the list so just like add we're going to create a new node with the element we pass in and the current node is going to equal head we always start at the beginning we need to keep track of the previous node and the current index is going to equal 0. so if index is more than length that means we've passed an index that's way bigger than the actual length of the linked list so we cannot add at that index when we return false if index equals zero that means we're trying to add the element to the head node so we'll set node.next or node is a node that we just passed in so the next element is now going to be the current node which would be the current head node and then we just set the head to equal the node that we passed in else we don't want the index to be the head node while current index is less than index we're going to go through each index until we find the correct index so current index increment we're going to set the previous node to equal the current node so we want to keep track of the previous node the current node is going to equal currentnode.next we're going to keep going through this while loop until we find the correct node so if we want to add a node as index 1 or the second node in the list once we get to that index we're going to set node.next equal to current node so our node.next is the node we passed in and we're going to set that to equal the current node which would be this index right here then we have to set previous node.next to equal the node that we're passing in and then we just increment the length and the last function i'm going to talk about is remove it now remove it and add it are very similar a lot of the lines are the same except we're not gonna create a new node the current node's gonna be the head we need a previous node the current index is gonna be zero here is a slightly different thing if the index is less than zero or if the index is more than or equal to length return null so we cannot remove a negative index and we cannot remove an index greater than the length of the list if index equals zero we're trying to remove the head node so we just set the head node to equal the current node.next so instead of the head pointer pointing to this node right here that head pointer is going to point to the next node right here else this part is just like the add at we're just going to keep going through each element on the list and once we find the element we want to remove like let's say we're removing this second element at index one we're going to set previousnode.next to equal current node.next we're going to set the previous node.next or this link is going to point to whatever was in the link to the current node or so this link is going to point to now this node right here and we're going to completely take out this one and then we're going to do length minus minus and return the node that we're removing and now we're just going to quickly show an example of using the linked list we're going to call the linked list conga because a linked list is kind of like a conga line and let me bring up the console so we're going to create this new linked list we're going to add some items kitchen puppy dog cat fish we're going to show the size we're going to remove the third item on the list so we'll run that and see we're going to remove cat now let's copy this we're gonna do element at then we'll try index aft and for the element we're gonna put puppy look i mean index of so we remove cat uh now we check the new element three which is going to be fish and the index of puppy is gonna be one uh kitchen would be zero coffee is one and the size is four well that's the linked list thanks for watching my name is beau carnes don't forget to subscribe and remember use your code for good\n"