8) Abstract Data Structures Lesson

Extend Python Linked Lists

3 min to complete · By Martin Breuss

There are many other methods that you could implement for a linked list in Python. Here are a few examples:

  • .insert(): Inserts a new node at a given index in the linked list.
  • .remove(): Removes the node at a given index from the linked list.
  • .find(): Returns the index of the first node with a given value or None if the value is not found.
  • .reverse(): Reverses the order of the nodes in the linked list.
  • .pop(): Removes and returns the value of the last node in the linked list.
  • .shift(): Removes and returns the value of the first node in the linked list.

Like always, there are multiple ways you could implement any of these. Below you can find some example code for the .insert() and .remove() methods:

class LinkedList:
    # ...

    def insert(self, index, value):
        if index < 0 or index > self.length:
            return
        new_node = Node(value)
        if index == 0:
            new_node.next = self.head
            self.head = new_node
        else:
            prev_node = self.get_node(index - 1)
            new_node.next = prev_node.next
            prev_node.next = new_node
        self.length += 1

    def remove(self, index):
        if index < 0 or index >= self.length:
            return
        if index == 0:
            self.head = self.head.next
        else:
            prev_node = self.get_node(index - 1)
            prev_node.next = prev_node.next.next
        self.length -= 1

    def __repr__(self):
        # ...

After you add these two methods to your linked list, you're able to insert and remove nodes at any index of the linked list. Give it a try!

If you want, you can attempt to build out your LinkedList class with some of the additional methods to train your skills and understanding of this data structure. You can use the list of example methods at the top of this page for inspiration.

Colorful illustration of a light bulb

Addition Resources

Summary: Extend the Python Linked Lists

There are many ways to improve your custom linked list, such as the following methods:

  • .insert()
  • .remove()
  • .find()
  • .reverse()
  • .pop()
  • .shift()