我创建了一个链表,但在互联网上查看后,我只看到包含2个类、1个节点和1个链表类的链表,现在我担心我的链表根本不是链表。
下面是我为链表编写的代码,但我现在担心这不是链表,而是更类似于二叉树。
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)
谢谢。
您的代码表示一个单独链接的列表。用于表示数据结构的类的数量以及这些类表示的数据结构不一定彼此有任何联系。