If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Sure! Let's implement the deletion functionality in a singly linked list using Python. We'll create methods to remove elements from the 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 remove(self, data): if not self.head: return 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() # Remove element 1 from the linked list linked_list.remove(1) print("Linked List after removing 1:") linked_list.display() # Remove element 7 from the linked list linked_list.remove(7) print("Linked List after removing 7:") linked_list.display()In this example, we have implemented the
NodeandLinkedListclasses. TheLinkedListclass has aremovemethod 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 removing 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 removing 1: 3 -> 7 -> 9 -> None Linked List after removing 7: 3 -> 9 -> NoneThe linked list is created and modified by removing 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