Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can a linked list class in python take a 'next' value in the constructor?

For convenience, I’d like to use a linked list Node class like the following:

a = Node(3)
b = Node(2, a)
c = Node(1, b) # c = (1) -> (2) -> (3)

I’ve tried the following class definition

class Node:
    def __init__(self, val: int, next_node: Node = None):
        self.val = val
        self.next = next_node

… but I’m getting a NameError about Node in the constructor.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I recognize that this is recursive, but nevertheless I’ve seen this done in other languages. Is this possible in Python?

>Solution :

Use typing.Self to refer to the Node type.

from typing import Self
class Node:
    def __init__(self, val: int, next_node: Self = None):

Alternatively, use the string 'Node'.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading