Syed Nahid
Syed Nahid

Reputation: 1

Trying to print the position of the element on the linked list, it seems to just print PS

trying to print the position of an element on the linked list via using a counter variable hop and returning it on success.

class Node_or_Element:

    def __init__(self,data): # Function to initialize the element's or the nodes
        self.data=data
        self.next=None

class Linked_list:
    def __init__(self):
        self.head=None
    
    def print_list(self):
        temp=self.head
        while(temp):
            print(temp.data)
            temp=temp.next
    
    def pos(self,data):
        curr=self.head
        while(curr==None):
            hop=0
            if(curr.data!=data):
                curr=curr.next
                hop+=1
            elif(curr.data==data):
                print(hop)
                
# Start with the empty list
llist = Linked_list()
llist.head = Node_or_Element(1)
second = Node_or_Element(2)
third = Node_or_Element(3)
  
llist.head.next = second  # Link first node with second
second.next = third # Link second node with the third node
third.next=None
  
llist.print_list()

llist.pos(2)

Expected output:

1
2
3
1

resulting output:

1
2
3

PS idk why it's printing PS

Upvotes: 0

Views: 31

Answers (1)

JohnyCapo
JohnyCapo

Reputation: 302

Yours pos function is the problem. You see, there is while(curr==None) but that never happens since curr=self.head...

I would advice you something like this:

def pos(self, l_data):
   curr = self.head
   index = 0

   while(True):
      if curr.data == l_data:
         return index
      elif curr.next != None:
         curr = curr.next
         index += 1
      else:
         return -1

EDIT: Also in your pos function there is line hop=0 which is inside the while so it will always be 0 every iteration!

Upvotes: 1

Related Questions