Skip to content

Instantly share code, notes, and snippets.

@ryukinix ryukinix/linked.py
Created Sep 9, 2018

Embed
What would you like to do?
A LinkedList implementation using Object Orientation in Python
from dataclasses import dataclass
from typing import T
"""
A naive Linked List implementation using dataclass as node.
"""
@dataclass
class Node:
data: T
next: 'Node'
class LinkedList:
def __init__(self):
self.root = None
def __delitem__(self, v):
node = self.root
prev = None
if self.root is not None and self.root.data == v:
self.root = self.root.next
return
while node is not None:
if node.data == v:
if prev is not None:
prev.next = node.next
else:
node = node.next
prev = node
node = node.next
return self
def __iter__(self):
node = self.root
while node is not None:
yield node.data
node = node.next
def __len__(self):
node = self.root
counter = 0
while node is not None:
counter += 1
node = node.next
return counter
def add(self, v):
self.root = Node(v, self.root)
return self
def append(self, v):
node = self.root
if node is not None:
while node.next is not None:
node = node.next
node.next = Node(v, None)
else:
self.add(v)
return self
def clear(self):
self.root = None
def index(self, i):
node = self.root
while i > 0:
node = node.next
i -= 1
return node.data
def __getitem__(self, k):
return self.index(k)
def __str__(self):
node = self.root
string = "["
while node is not None:
string += repr(node.data)
if node.next is None:
break
else:
string += ", "
node = node.next
string += "]"
return string
__repr__ = __str__
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.