Skip to content

Commit cd0b473

Browse files
committed
Fix type annotations for linked_stack.py
1 parent ccff4c1 commit cd0b473

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

data_structures/stacks/linked_stack.py

+16-13
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,22 @@
11
""" A Stack using a linked list like structure """
22
from __future__ import annotations
33

4-
from typing import Any
4+
from collections.abc import Iterator
5+
from typing import Generic, Optional, TypeVar
56

7+
T = TypeVar("T")
68

7-
class Node:
8-
def __init__(self, data):
9+
10+
class Node(Generic[T]):
11+
def __init__(self, data: T):
912
self.data = data
10-
self.next = None
13+
self.next: Optional[Node[T]] = None
1114

12-
def __str__(self):
15+
def __str__(self) -> str:
1316
return f"{self.data}"
1417

1518

16-
class LinkedStack:
19+
class LinkedStack(Generic[T]):
1720
"""
1821
Linked List Stack implementing push (to top),
1922
pop (from top) and is_empty
@@ -44,15 +47,15 @@ class LinkedStack:
4447
"""
4548

4649
def __init__(self) -> None:
47-
self.top: Node | None = None
50+
self.top: Optional[Node[T]] = None
4851

49-
def __iter__(self):
52+
def __iter__(self) -> Iterator[T]:
5053
node = self.top
5154
while node:
5255
yield node.data
5356
node = node.next
5457

55-
def __str__(self):
58+
def __str__(self) -> str:
5659
"""
5760
>>> stack = LinkedStack()
5861
>>> stack.push("c")
@@ -63,7 +66,7 @@ def __str__(self):
6366
"""
6467
return "->".join([str(item) for item in self])
6568

66-
def __len__(self):
69+
def __len__(self) -> int:
6770
"""
6871
>>> stack = LinkedStack()
6972
>>> len(stack) == 0
@@ -87,7 +90,7 @@ def is_empty(self) -> bool:
8790
"""
8891
return self.top is None
8992

90-
def push(self, item: Any) -> None:
93+
def push(self, item: T) -> None:
9194
"""
9295
>>> stack = LinkedStack()
9396
>>> stack.push("Python")
@@ -101,7 +104,7 @@ def push(self, item: Any) -> None:
101104
node.next = self.top
102105
self.top = node
103106

104-
def pop(self) -> Any:
107+
def pop(self) -> T:
105108
"""
106109
>>> stack = LinkedStack()
107110
>>> stack.pop()
@@ -125,7 +128,7 @@ def pop(self) -> Any:
125128
self.top = self.top.next
126129
return pop_node.data
127130

128-
def peek(self) -> Any:
131+
def peek(self) -> T:
129132
"""
130133
>>> stack = LinkedStack()
131134
>>> stack.push("Java")

0 commit comments

Comments
 (0)