Home > Software design >  Can a linked list class in python take a 'next' value in the constructor?
Can a linked list class in python take a 'next' value in the constructor?

Time:01-31

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.

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

CodePudding user response:

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'.

CodePudding user response:

You can define a linked list class in Python by utilizing a recursive structure similar to the one you've given an example of. To avoid the NameError you are experiencing, you must put the class definition outside of the init method. Here is your code in corrected form:

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


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

It should be noted that the type hint for next node substitutes the string literal "Node" for the class name Node. Due to this, Python is able to identify the class reference even though it hasn't yet been defined.

  • Related