If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Sure! Here's the Python code to implement the deletion functionality in a singly linked list:
pythonCopy code
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self, data): new_node = Node(data) if not self.head: self.head = new_node else: current = self.head while current.next: current = current.next current.next = new_node def delete(self, data): if not self.head: return # If the node to be deleted is the head node if self.head.data == data: self.head = self.head.next return current = self.head while current.next: if current.next.data == data: current.next = current.next.next return current = current.next def display(self): current = self.head while current: print(current.data, end=" -> ") current = current.next print("None") # Example usage: if __name__ == "__main__": linked_list = LinkedList() # Append elements to create the linked list linked_list.append(3) linked_list.append(7) linked_list.append(1) linked_list.append(9) print("Original Linked List:") linked_list.display() # Delete element 1 from the linked list linked_list.delete(1) print("Linked List after deleting 1:") linked_list.display() # Delete element 7 from the linked list linked_list.delete(7) print("Linked List after deleting 7:") linked_list.display()In this code, we have implemented the
NodeandLinkedListclasses. TheLinkedListclass has adeletemethod that removes elements from the linked list. We then create a linked list object and use theappendmethod to add elements (3, 7, 1, and 9) to create the linked list.Finally, we demonstrate the deletion operation by deleting elements 1 and 7 from the linked list. We display the linked list after each deletion to see the changes.
The output will be:
rustCopy code
Original Linked List: 3 -> 7 -> 1 -> 9 -> None Linked List after deleting 1: 3 -> 7 -> 9 -> None Linked List after deleting 7: 3 -> 9 -> NoneThe linked list is created and modified by deleting elements 1 and 7, resulting in the final linked list with elements 3 and 9.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support