I have created a linked list, but after looking on the internet I only see linked lists containing 2 classes, 1 node and 1 linked list class and now I am worried mine is not a linked list at all.
Below is code I have written for a linked list, but am now worried this isn't a linked list and instead more similar to a binary tree.
import random
cache = {}
class Node:
def __init__(self, data):
self.head = None
self.data = data
def insert(self, data):
if self.data:
if self.head is None:
self.head = Node(data)
else:
self.head.insert(data)
else:
self.data = data
def PrintList(self):
if self.head:
self.head.PrintList()
print( self.data ),
def ListLength(self, length = 0):
if self.head:
return self.head.ListLength(length 1)
return length
def PrintListRandomKnownNodes(self, randnode, count = 0):
if randnode == count:
return self.data
if self.head:
return self.head.PrintListRandomKnownNodes(nodeamount, count 1)
return self.data
def printRandomUnknownNodes(self):
if self.data:
cache[self] = self.data
if self.head:
return self.head.printRandomUnknownNodes()
res = random.choice(list(cache.values()))
return res
LList = Node(1)
nodes = random.randrange(5, 10)
for x in range(0, 10):
# LList.counter = LList.counter 1
LList.insert(x random.randrange(5, 100))
LList.PrintList()
ListLength = LList.ListLength()
print("list length is ", ListLength)
randomNum = random.randint(0, ListLength)
print("randomnum",randomNum)
randomnode = LList.PrintListRandomKnownNodes(ListLength, randomNum)
print("random known node amount node data is:", randomnode)
cache = {}
randomunknownnode = LList.printRandomUnknownNodes()
print("random unknown node amount data is:", randomunknownnode)
Thanks.
CodePudding user response:
Your code represents a singly linked list. The number of classes used to represent a data structure and what data structure those classes represent do not necessarily have any connection with each other.