Maybe it’s out of topic. What should I do, if I want to delete the values in LinkedList. while in the LinkedList, there are several nodes that have the same value. How do I delete all nodes that match the value I want when calling the remove_node method. Here is my code.
class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next_node(self):
return self.next_node
def set_next_node(self, next_node):
self.next_node = next_node
# Our LinkedList class
class LinkedList:
def __init__(self, value=None):
self.head_node = Node(value)
def get_head_node(self):
return self.head_node
def insert_beginning(self, new_value):
new_node = Node(new_value)
new_node.set_next_node(self.head_node)
self.head_node = new_node
def stringify_list(self):
string_list = ""
current_node = self.get_head_node()
while current_node:
if current_node.get_value() != None:
string_list += str(current_node.get_value()) + "\n"
current_node = current_node.get_next_node()
return string_list
def remove_node(self, value_to_remove):
current_node = self.get_head_node()
if current_node.get_value() == value_to_remove:
self.head_node = current_node.get_next_node()
else:
while current_node:
next_node = current_node.get_next_node()
if next_node.get_value() == value_to_remove:
current_node.set_next_node(next_node.get_next_node())
current_node = None
else:
current_node = next_node
Jika saya jalankan code dibawah ini
ll = LinkedList(5)
ll.insert_beginning(70)
ll.insert_beginning(5)
ll.insert_beginning(90)
ll.insert_beginning(70)
ll.insert_beginning(90)
print(ll.stringify_list())
ll.remove_node(90)
print(ll.stringify_list())
the output will be like this

From the results above, it can be concluded, we have to delete the values from the nodes one by one. How do I if I want to delete all nodes with the value I gave to the remove_node method. For example, I want to delete all nodes with a value of 70. The result will be when we run remove_node (70)
then the output of nodes with a value of 70 will be deleted.