From 2fcee6d49294f630f3bea81da073d9dc650eb85f Mon Sep 17 00:00:00 2001 From: Isidro Arias Date: Fri, 18 Apr 2025 13:48:36 +0200 Subject: [PATCH] Generic type hint in DDL Instead of forcing int --- .../linked_list/doubly_linked_list_two.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/data_structures/linked_list/doubly_linked_list_two.py b/data_structures/linked_list/doubly_linked_list_two.py index 8c93cddd5d31..01c9e1d47644 100644 --- a/data_structures/linked_list/doubly_linked_list_two.py +++ b/data_structures/linked_list/doubly_linked_list_two.py @@ -10,12 +10,14 @@ """ from dataclasses import dataclass -from typing import Self +from typing import Self, TypeVar + +Data = TypeVar("Data") @dataclass -class Node: - data: int +class Node[Data]: + data: Data previous: Self | None = None next: Self | None = None @@ -52,7 +54,7 @@ def __str__(self): current = current.next return " ".join(str(node) for node in nodes) - def __contains__(self, value: int): + def __contains__(self, value: Data): current = self.head while current: if current.data == value: @@ -87,7 +89,7 @@ def set_tail(self, node: Node) -> None: else: self.insert_after_node(self.tail, node) - def insert(self, value: int) -> None: + def insert(self, value: Data) -> None: node = Node(value) if self.head is None: self.set_head(node) @@ -116,7 +118,7 @@ def insert_after_node(self, node: Node, node_to_insert: Node) -> None: node.next = node_to_insert - def insert_at_position(self, position: int, value: int) -> None: + def insert_at_position(self, position: int, value: Data) -> None: current_position = 1 new_node = Node(value) node = self.head @@ -128,7 +130,7 @@ def insert_at_position(self, position: int, value: int) -> None: node = node.next self.set_tail(new_node) - def get_node(self, item: int) -> Node: + def get_node(self, item: Data) -> Node: node = self.head while node: if node.data == item: