Skip to content

Instantly share code, notes, and snippets.

@Edald123
Last active July 19, 2021 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Edald123/6c2629fdd977f8dfea25cdfcc7d3d1d2 to your computer and use it in GitHub Desktop.
Save Edald123/6c2629fdd977f8dfea25cdfcc7d3d1d2 to your computer and use it in GitHub Desktop.
Linked List in Python
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 += 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
def remove_all_occurrences(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()
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 = current_node.get_next_node()
else:
current_node = next_node
# Test cases:
ll = LinkedList(5)
ll.insert_beginning(70)
ll.insert_beginning(5675)
ll.insert_beginning(90)
ll.insert_beginning(70)
print(ll.stringify_list())
ll.remove_node(5)
print(ll.stringify_list())
ll.remove_all_occurrences(70)
print(ll.stringify_list())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment