Remove Node

In this lesson, you will learn how to remove a node from a circular linked list using Python.

We'll cover the following...

In this lesson, we investigate how to remove nodes in a circular linked list and code the method in Python.

There is an assumption that we will make before diving into the implementation:

  • The occurrences of nodes will be unique, i.e., there will be no duplicate nodes in the circular linked list that we’ll test on.

This is because the code that we will write will only be responsible for removing the first occurrence of the key provided to be deleted.

Implementation

Now let’s go ahead and jump to the implementation of remove in Python:

Press + to interact
def remove(self, key):
if self.head:
if self.head.data == key:
cur = self.head
while cur.next != self.head:
cur = cur.next
if self.head == self.head.next:
self.head = None
else:
cur.next = self.head.next
self.head = self.head.next
else:
cur = self.head
prev = None
while cur.next != self.head:
prev = cur
cur = cur.next
if cur.data == key:
prev.next = cur.next
cur = cur.next

Explanation

The code is divided into parts based on whether or not we are deleting the ...