From eede65a423f0e0d6dc2d15776d95464d0140eca0 Mon Sep 17 00:00:00 2001 From: Sweta Negi Date: Tue, 28 Oct 2025 17:00:19 +0530 Subject: [PATCH] Implement node removal and sum methods in linked list Added methods to remove a node by value and to sum all node values in the linked list. --- .../add_and_subtract_nodes_in_linked_list.py | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/python/add_and_subtract_nodes_in_linked_list.py b/python/add_and_subtract_nodes_in_linked_list.py index 48ae72b9..fa8c5a2c 100644 --- a/python/add_and_subtract_nodes_in_linked_list.py +++ b/python/add_and_subtract_nodes_in_linked_list.py @@ -26,7 +26,40 @@ def subtract(self, value): while current: current.data -= value current = current.next + + #remove_nod + def remove_node(self,value): + """Remove first occurence of a node + with the given value""" + current = self.head + + #If list is empty + if not current: + print("List is empty.") + return + #If head node itself holds the value + if current.data == value: + self.head = current.next + + #If not found + if not current: + print(f"Value{value}not foundin list.") + return + + #unlink the code + prev.next = current.next + + #sum_node + def sum_nodes(self): + """Return the sum of all node vlaues""" + total = 0 + current = self.head + while current: + total +=current.data + current = current.next + return total + # Print the linked list def print_list(self): current = self.head @@ -48,3 +81,10 @@ def print_list(self): ll.subtract(5) print("After subtracting 5 from each node:") ll.print_list() + +print("/nRemoving node with value 10.") +11.remove_node(10) +11.print_list() + +print("\nSum of nodes:",11.sum_nodes()) +