Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can Linked Lists be only a single class?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading