## DEV Community is a community of 786,923 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Abu Hurayra

Posted on

# Deletion From a Simple Linked List Using Python

### Deleting a node from a linked list is straightforward but there are a few cases we need to account for:

• 1. The list is empty
• 2. The node to remove is the only node in the linked list
• 3. We are removing the head node
• 4. We are removing the tail node
• 5. The node to remove is somewhere in between the head and tail node
• 6. The item to remove does not exist in the linked list.

## Step 1: If the list is empty then print a message and return.

``````def delete(self, key):
# If the list is empty
print('Deletion Error: The list is empty.')
return
``````

``````    # If the key is in head
return
``````

## Step 3: Find the first occurrence of the key in the linked list.

``````    # Find position of first occurrence of the key
while current:
if current.data == key:
break
previous = current
current = current.next
``````

## If the key was found then point the previous node to the next node of the key. Otherwise print an error message.

``````    # If the key was not found
if current is None:
else:
previous.next = current.next
``````

## The complete code is given below:

``````class Node:
def __init__(self, data):
self.data = data
self.next = None

def __init__(self):

def printList(self):
if not temp:
print('List is empty.')
return
else:
print('Start:', end=' ')
while temp:
print(temp.data, end=' -> ')
temp = temp.next
print('end.')

def insert(self, data):
new_node = Node(data)

# If the linked list is empty

# If the data is smaller than the head

else:
# Locate the node before the insertion point
while current.next and new_node.data > current.next.data:
current = current.next

# Insertion
new_node.next = current.next
current.next = new_node

def delete(self, key):
# If the list is empty
print('Deletion Error: The list is empty.')
return

# If the key is in head
return

# Find position of first occurrence of the key
while current:
if current.data == key:
break
previous = current
current = current.next

if current is None:
else:
previous.next = current.next

if __name__=='__main__':
# Create an object
print('')

# Insert some nodes
LL.insert(10)
LL.insert(12)
LL.insert(8)
LL.insert(11)
LL.insert(10)

LL.printList()
LL.delete(7)
LL.delete(8)
LL.delete(13)
LL.printList()

``````

References: