Home > database >  make a for loop for linked list class
make a for loop for linked list class

Time:01-17

i want to iterate over my custom class linked list, could anyone help me for that, i couldn't find it straightforward in web.

the problem is when i want to iterate over linked list its give me an error and said the linked list don't have a loop in it.

i want to make it iterable with __iter__ and __next__ or some other easier algorithms.

here are few lines of my code:

class node:
      def __init__(self, data=None):
          self.data = data
          self.next = None
class linkedList:
      def __init__(self):
         self.head = node()
         self._len = 0

      def add(value):
         self._len  = 1
         newNode = node(value)
         curNode = self.head

         while curNode.next != None:
               curNode = curNode.next
         
         curNode.next = newNode

CodePudding user response:

First of all: your code doesn't work: add is missing the self parameter. It should be declared as add(self, value).

To make your class instance iterable, define __iter__, and use a loop much like you have used in the add method, except that you don't need to look ahead in the while condition:

class linkedList:
    def __init__(self):
        self.head = node()
        self._len = 0

    def __iter__(self):
        curNode = self.head.next  # Skip head, as it is a dummy node
        while curNode:
            yield curNode.data
            curNode = curNode.next

Now you can use the feature that an instance is iterable:

lst = linkedList()
lst.add(19)
lst.add(33)
print(*lst)  # splash the values to print them
# or with a loop
for value in lst:
    print(value)
  •  Tags:  
  • Related