链表可以只有一个class吗?

Can Linked Lists be only a single class?

我创建了一个链表,但是在网上查看后我只看到包含2个classes,1个节点和1个链表class的链表,现在我担心我的是根本不是链表。

下面是我为链表编写的代码,但现在我担心这不是链表,而是更类似于二叉树。

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)



谢谢。

您的代码代表一个单链表。 类用来表示一个数据结构的个数和类代表什么数据结构之间没有必然联系