Home > Software design >  Linked List Implementation Python , printing none as first node
Linked List Implementation Python , printing none as first node

Time:02-04

I have created a linked list implementation and everything seems to be working however when I print the linked list it begins with None and then continues to print the numbers accordingly. I am not sure why this happens because if the incoming value is the first value it assigns head to that value

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

class LinkedList:

def __init__(self):
  self.head = Node()

def append(self, value):

  new_node = Node(value)
  new_node.value = value
  new_node.next = None
  if self.head is None:
      self.head = new_node
  else:
    tmp = self.head
    while tmp.next is not None:
        tmp = tmp.next
    tmp.next = new_node

def show(self):
    start = self.head
    while start.next is not None:
        print(start.value," -> ",end="")
        start = start.next
    print(start.value)


linked_list = LinkedList()
linked_list.append(4)
linked_list.append(3)
linked_list.append(8)
linked_list.append(2)
linked_list.append(9)
linked_list.show()

CodePudding user response:

You set self.head = Node() in the __init__ function, which would make the first value in your linkedlist None. Maybe you meant to set self.head = None?

CodePudding user response:

In LinkedList constructor you have set self.head=Node(). you may replace it with None but it throws an error or it runs infintly.

In def show(self): point the start node (val=None) to the next node i.e start=self.head.next

start=self.head

None -> 4 -> 3 -> 8 -> 2 -> 9

After moving the pointer

start=self.head.next

4 -> 3 -> 8 -> 2 -> 9

  •  Tags:  
  • Related