Singly LinkedList
1. Node
class Node:
def __init__(self ,data, next = None) -> None:
self.data = data
self.index = None
self.next = next
2. LinkedList
class SinglyLinkedList:
def __init__(self) -> None:
self.head = None
def prepend(self, node : Node) -> None:
node.next = self.head
self.head = node
def append(self, node : Node) -> None:
if self.head is None:
self.head = node
else:
i = self.head
while i.next is not None:
i = i.next
i.next = node
def show(self) -> list:
result = []
i = self.head
while i:
result.append(i.data)
i = i.next
return result
def count(self, val):
cnt = 0
i = self.head
while i:
if i.data == val:
cnt += 1
i = i.next
return cnt
a = Node(0)
b = Node(1)
c = Node(2)
d = Node(3)
singlylist1 = SinglyLinkedList()
singlylist2 = SinglyLinkedList()
singlylist1.prepend(a)
singlylist1.prepend(b)
singlylist1.prepend(c)
singlylist1.prepend(d)
singlylist1.show()
[3, 2, 1, 0]
e = Node(10)
f = Node(12)
g = Node(9)
h = Node(53)
singlylist2.append(e)
singlylist2.append(f)
singlylist2.append(g)
singlylist2.append(h)
singlylist2.show()
[10, 12, 9, 53]
singlylist2.count(8)
0
i = Node(13)
j = Node(11)
k = Node(28)
l = Node(35)
singlylist3 = SinglyLinkedList()
singlylist3.sort(i)
singlylist3.sort(j)
singlylist3.sort(k)
singlylist3.sort(l)
singlylist3.show()
[13]