Search code examples
pythonlinked-listnodes

How to return elements after building a list of nodes in python


Suppose we have the Node class and b_list function:

class Node:
    def __init__(self, elm, nxt):
        self.elm = elm
        self.nxt = nxt
def b_list(first, end):
    if first>= end:
        return None 
    else:
        return Node(first, b_list(first+1, end))

How can I create the "showelm (h)" function to yield the elements in the linked list h. For example:

print(list(showelm(b_list(0, 10))))

Solution

  • Not fully sure I understand what you're trying to accomplish with the last line of code there, but I assume you're trying to first create your linked list, and then print each nodes value in sequence afterwards?

    def showelm(node):
        while node:
            print(node.elm)
            node = node.nxt
    
    nodeval = b_list(0, 10)
    showelm(nodeval)