Singly Linked List
We can initiate a singly linked list (SLList) as:
class Node:
def __init__(self, val, next): # Initiates Node.
self.val = val
self.next = next
class SLList:
def __init__(self, val): # Initiates SLList.
self.head = Node(val, None)
self.size = 1
def __str__(self):
a = self
out = []
while a.head:
out.append(a.head.val)
a.head = a.head.next
return str(out)
def size(self):
return self.size
def insert(self, val, pos=None):
if pos is None: # Auto sets insert position to last position.
pos = self.size
if pos > self.size:
print("Index too large!")
return
a = self.head # Removing abstraction barrier.
while pos - 1 > 0:
a = a.next
pos -= 1
a.next = Node(val, a.next)
self.size += 1