cumin
cumin

Reputation: 491

implementing __next__() in python linked list

I would like to retrieve a particular node in a linked list by iterating a specified number of times; for example, to retrieve the 4th node. By implementing __iter__(), I can iterate with a for loop, but I don't know how get a next() function to work. I've commented out my attempt at a next() function; when it is left in, I still get AttributeError: 'LinkedList' object has no attribute 'next'

EDIT: I would like the getNode(self, loc) to return a node at the specified location by calling next() if possible.

Here is the Node and LinkedList classes:

class Node:
    def __init__(self,  data = None):
        self.data = data
        self.next = None
        
    def __repr__(self):
        return str(self.data)
        
class LinkedList:
    def __init__(self, nodes = None):
        self.head = None
        if nodes is not None:
            node = Node(data=nodes.pop(0))
            self.head = node
            for elem in nodes:
                node.next = Node(data=elem)
                node = node.next
        
    def __repr__(self):
        node = self.head
        nodes = []
        while node is not None:
            nodes.append(str(node.data))
            node = node.next
        nodes.append("None")
        return " -> ".join(nodes)
    
    def __iter__(self):
        node = self.head
        while node is not None:
            yield node
            node = node.next
    
    # def __next__(self):
    #     return self.next
    

    def getNode(self,loc):
        cnt = 0
        for i in self:
            if cnt < loc:
                cnt += 1
            else:
                break 
        return i
            
        
ll = LinkedList([1,2,3,4,5])
print(ll)
print(ll.getNode(3))

for i in range(3):
    print(ll.next())

[OUTPUT] I 1 -> 2 -> 3 -> 4 -> 5 -> None 4 Traceback (most recent call last):

  File "/Users/jk/_python_source/misc_python/_mymisc/Leetcode work/LinkedList.py", line 53, in <module>
    print(ll.next())

AttributeError: 'LinkedList' object has no attribute 'next'

Upvotes: 0

Views: 999

Answers (2)

Paul M.
Paul M.

Reputation: 10819

You're doing way more work than you have to. Once you've implemented __iter__, the rest falls into place. You can use it to implement pretty much all your other functions, like get_node, __str__ or __repr__, etc.

class Node:

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

    def __str__(self):
        return str(self.value)


class LinkedList:

    def __init__(self):
        self.head = None

    def add(self, value):
        if self.head is None:
            self.head = Node(value)
        else:
            for cursor in self:
                pass
            cursor.next = Node(value)
        return self

    def get_node(self, node_index):
        for index, node in enumerate(self):
            if index == node_index:
                break
        else:
            return None
        return node

    def __str__(self):
        return " -> ".join(map(str, self))

    def __iter__(self):
        cursor = self.head
        while cursor is not None:
            yield cursor
            cursor = cursor.next

ll = LinkedList().add(1).add(2).add(3)
print(ll)

for node_index in 0, 1, 2, 3:
    print("The node at index {} is {}".format(node_index, ll.get_node(node_index)))

Output:

1 -> 2 -> 3
The node at index 0 is 1
The node at index 1 is 2
The node at index 2 is 3
The node at index 3 is None
>>> 

Upvotes: 1

cumin
cumin

Reputation: 491

ThisgetNode()also works:

def getNode(self,loc):
    it = iter(self)
    for i in range(loc):
        next(it)
    return next(it)

Upvotes: 0

Related Questions