I am learning basic data structures in Python. I'm not confident enough if my implementations are OK or I miss any corner cases. So please check my code for Singly Linked List and Let me know where I can improve.
"""
Singly Linked List Implementation
"""
class Node:
"""
Constructor for Node class
takes 3 arguments. 'value' for Node's value and 'next' for next Node.
Default are Node.
Return Node object
"""
def __init__(self, value=None, next=None):
self.value = value
self.next: Node = next
def __repr__(self):
return str(self.value)
'''
returns the string of the node value
'''
def __str__(self) -> str:
return str(self.value)
class LinkedList:
'''
Constructor requires a value
'''
def __init__(self, value):
self.head = Node(value=value)
'''
returns iterator to iterate through the LinkedList
'''
def __iter__(self):
current = self.head
while current:
yield current
current = current.next
'''
To print the LinkedList object like
4 -> 5 -> 7 -> 10
'''
def __repr__(self) -> str:
values = []
current = self.head
while current:
values.append(str(current.value))
current = current.next
return " -> ".join(values)
'''
append at the end of the LinkedList
'''
def append(self, value):
if not self.head:
self.head = Node(value=value)
return
current = self.head
while current.next:
current = current.next
current.next = Node(value=value)
def prepend(self, value):
new_head = Node(value=value)
new_head.next = self.head
self.head = new_head
def delete(self, value):
if not self.head:
return
'''
if HEAD is the desired Node then unlink it and make next Node as HEAD
'''
if self.head.value == value:
self.head = self.head.next
return
'''
Bypass the Node with value to unlink it.
If next Node has the desired value to delete, then
make next.next as next Node unlink next
4->5->7
4->7
'''
current = self.head
while current.next:
if current.next.value == value:
current.next = current.next.next
return
current = current.next
Test code:
# 4->5->7->10
a = LinkedList(4)
a.append(5)
a.append(7)
a.append(10)
print("after adding")
print(a)
a.delete(7)
print("after deleting 7")
print(a)
a.prepend(2)
print("after prepending 2")
print(a)
a.delete(10)
print("after deleting 10")
print(a)
a.delete(10)
Output
after adding
4 -> 5 -> 7 -> 10
after deleting 7
4 -> 5 -> 10
after prepending 2
2 -> 4 -> 5 -> 10
after deleting 10
2 -> 4 -> 5
__iter__
is badly broken. \$\endgroup\$