Skip to content

Instantly share code, notes, and snippets.

View wanderindev's full-sized avatar

Javier Feliu wanderindev

View GitHub Profile
from typing import Any, Union
class Node:
"""A linked list node implementation"""
def __init__(self, node_data: Any) -> None:
"""Initialize the node with the given data and pointing to None"""
self._data = node_data
self._next_node = None
class SinglyLinkedList:
"""A singly linked list implementation"""
def __init__(self) -> None:
"""Initialize a singly link list where the head is None"""
self.head = None
def __str__(self) -> str:
"""Return a string representation of the linked list"""
sll_nodes = []
def get_last_node(self) -> "Node":
"""Return the last node in the linked list"""
current_node = self.head
while current_node.next_node is not None:
current_node = current_node.next_node
return current_node
def get_node(self, node_data: Any) -> Union["Node", None]:
"""Return the first node whose data is node_data or None"""
current_node = self.head
def is_empty(self) -> bool:
"""Returns True is the linked list is empty"""
return not self.head
def add_front(self, new_data: Any) -> None:
"""Add a node to the front of the linked list"""
new_node = Node(new_data)
new_node.next_node = self.head
self.head = new_node
def add_back(self, new_data: Any) -> None:
"""Add a node to the back of the linked list"""
self.get_last_node().next_node = Node(new_data)
def add_after(self, node_data: Any, new_data: Any) -> None:
"""Add a node after the first node whose data is node_data"""
new_node = Node(new_data)
insert_at_node = self.get_node(node_data)
if insert_at_node:
new_node.next_node = insert_at_node.next_node
insert_at_node.next_node = new_node
def add_before(self, node_data: Any, new_data: Any) -> None:
"""Add a node before the first node whose data is node_data"""
new_node = Node(new_data)
insert_at_node = self.get_prev_node(node_data)
if insert_at_node:
new_node.next_node = insert_at_node.next_node
insert_at_node.next_node = new_node
else:
self.add_front(new_data)
def pop(self) -> Union[Any, None]:
"""Return and remove the node at the front of the linked list"""
if self.is_empty():
return None
node_to_pop = self.head
self.head = self.head.next_node
return node_to_pop.data
def remove(self, node_data: Any) -> None:
"""Remove the first node whose data is node_data"""
if not self.is_empty():
prev_node = self.get_prev_node(node_data)
prev_node.next_node = prev_node.next_node.next_node