Python LinkedList not created

Hi,
I have created a LinkedList program. There is no error but it looks like that list is not created. The program is:

class Node:
    def __init__(self, id, name):
        self.id = id
        self.name = name
        self.next = None



class LinkedList:

    def __init__(self): #instance variables
       self.head = None
       self.tail = None
       #self.last = None

    def create_4_Element_List(self):
       newNode = Node(100, "SSUET100") # newNode is an object having 2 instance variables: data and next
       head = newNode
       tail = newNode
       for i in range(10):
          print("i= "+ str(i))
          i = i + 101
          name = "SSUET" + str(i)
          newNode = Node(i, "SSUET")
          tail.next = newNode
          tail = newNode

    def printList(self):
       temp = self.head
       while (temp):
          print("name=", temp.name)
          temp = temp.next


if __name__ == '__main__':
    # Start with the empty list
    llist = LinkedList()
    print("Testing1")
    llist.create_4_Element_List()
    print("Testing2")
    llist.printList()
    print("Testing3")

output:
The output of the program is:

Testing1

i= 0

i= 1

i= 2

i= 3

i= 4

i= 5

i= 6

i= 7

i= 8

i= 9

Testing2

Testing3

Somebody please guide me.

Zulfi.

Hi @Zulfi6000, you’re creating a linked list of nodes but not assigning any node to self, so the list just goes nowhere. For your print method to work, you’d at least have to assign the first node to self.head:

class LinkedList:

    def __init__(self):
        self.head = None

    def create_list(self):
        self.head = current = Node(100, "SSUET100")

        for i in range(10):
            print("i= " + str(i))
            name = "SSUET" + str(i + 101)
            current.next = current = Node(i, name)

    def print_list(self):
        current = self.head

        while (current):
            print("name=", current.name)
            current = current.next
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.