Skip to content

Instantly share code, notes, and snippets.

@codecademydev codecademydev/script.py Secret
Created Jul 21, 2019

Embed
What would you like to do?
Codecademy export
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
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.append(current_node.get_value())
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
def remove_all_specific_nodes(self, value_to_remove):
count = self.stringify_list().count(value_to_remove)
while (count != 0):
self.remove_node(value_to_remove)
count -= 1
print("All instances of '{}' have been removed from the linked list.".format(value_to_remove))
ll = LinkedList(5)
for i in range(10, 21):
ll.insert_beginning(i)
ll.insert_beginning(12)
ll.insert_beginning(12)
ll.remove_all_specific_nodes(12)
print(ll.stringify_list())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.