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

Linked List in python is not showing the correct results

I want my code to print numbers from 0 to 5, instead it prints only 0 as output. Can anyone correct the code.
code:

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

class LinkedList:
  def __init__(self):
    self.head = None
  def display(self):
    ptr = self.head
    while ptr is not None:
      print(ptr.value)
      ptr = ptr.next

l1 = LinkedList()
ptr = l1
ptr.head = Node(0)
ptr.head.next = None
a = [1, 2, 3, 4, 5]

for i in a:
    dummy = Node(i)
    ptr.next = dummy
    ptr = ptr.next

# Displaying the linked list
l1.display()

I tried to build a simple linked list in python and was trying to print the numbers that were stored in the linked list, but there is something wrong with my code and it isn’t working as I wanted it to be.

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 :

The issue is because when you initialized ptr, and set ptr.head.next = None, you didn’t move the ptr forward.

Try:


class Node:

    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:

    def __init__(self):
        self.head = None

    def display(self):
        ptr = self.head
        while ptr is not None:
            print(ptr.value)
            ptr = ptr.next

l1 = LinkedList()
ptr = l1
ptr.head = Node(0)
ptr.head.next = None
ptr = ptr.head
a = [1, 2, 3, 4, 5]

for i in a:
    dummy = Node(i)
    ptr.next = dummy
    ptr = ptr.next

# Displaying the linked list
l1.display()

Running it produces:

0
1
2
3
4
5

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