Skip to content

Instantly share code, notes, and snippets.

@ZechCodes
Created April 30, 2023 13:35
Show Gist options
  • Save ZechCodes/13a31d45659d3852069b360d4b30889f to your computer and use it in GitHub Desktop.
Save ZechCodes/13a31d45659d3852069b360d4b30889f to your computer and use it in GitHub Desktop.
A simple linked list implementation in Python for the weekly coding prompt on the Beginner.Codes Discord server. Join now https://beginner.codes/discord
from typing import Generic, TypeVar
T = TypeVar("T")
class Node(Generic[T]):
def __init__(self, value: T, head: "Node | None" = None, next_node: "Node | None" = None):
self.head = self if head is None else head
self.next = next_node
self.value = value
if head is None and next_node is not None:
self._set_head_node(self)
def append(self, value: T) -> "Node[T]":
tail = self._get_tail_node()
tail.next = Node[T](value, self.head)
return tail.next
def _get_tail_node(self) -> "Node[T]":
node = self
while node.next is not None:
node = node.next
return node
def insert(self, value: T) -> "Node[T]":
self.next = Node[T](value, self.head, self.next)
return self.next
def delete(self) -> "Node[T] | None":
if self.head is self:
self._set_head_node(self.next)
else:
self._remove_node()
return self.next
def _remove_node(self):
previous = self._get_previous_node()
previous.next = self.next
return self.next
def _set_head_node(self, new_head: "Node[T]"):
node = self.next
while node is not None:
node.head = new_head
node = node.next
def _get_previous_node(self) -> "Node[T] | None":
if self.head is self:
return None
node = self.head
while node is not None and node.next is not self:
node = node.next
return node
def __repr__(self):
return f"<Node{':HEAD' if self.head is self else ''}{'' if self.next else ':TAIL'} {self.value!r}>{self.next if self.next else ''}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment