Skip to content

Commit 9a03919

Browse files
authored
[mypy] Fix type annotations for stack_using_dll.py (#5577)
* Fix mypy annotations for stack_using_dll.py * Replace Optional with inline union type
1 parent c0ed031 commit 9a03919

File tree

1 file changed

+24
-16
lines changed

1 file changed

+24
-16
lines changed

data_structures/stacks/stack_using_dll.py

+24-16
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,21 @@
11
# A complete working Python program to demonstrate all
22
# stack operations using a doubly linked list
33

4+
from __future__ import annotations
45

5-
class Node:
6-
def __init__(self, data):
6+
from typing import Generic, TypeVar
7+
8+
T = TypeVar("T")
9+
10+
11+
class Node(Generic[T]):
12+
def __init__(self, data: T):
713
self.data = data # Assign data
8-
self.next = None # Initialize next as null
9-
self.prev = None # Initialize prev as null
14+
self.next: Node[T] | None = None # Initialize next as null
15+
self.prev: Node[T] | None = None # Initialize prev as null
1016

1117

12-
class Stack:
18+
class Stack(Generic[T]):
1319
"""
1420
>>> stack = Stack()
1521
>>> stack.is_empty()
@@ -35,10 +41,10 @@ class Stack:
3541
2->1->0->
3642
"""
3743

38-
def __init__(self):
39-
self.head = None
44+
def __init__(self) -> None:
45+
self.head: Node[T] | None = None
4046

41-
def push(self, data):
47+
def push(self, data: T) -> None:
4248
"""add a Node to the stack"""
4349
if self.head is None:
4450
self.head = Node(data)
@@ -49,32 +55,34 @@ def push(self, data):
4955
new_node.prev = None
5056
self.head = new_node
5157

52-
def pop(self):
58+
def pop(self) -> T | None:
5359
"""pop the top element off the stack"""
5460
if self.head is None:
5561
return None
5662
else:
63+
assert self.head is not None
5764
temp = self.head.data
5865
self.head = self.head.next
59-
self.head.prev = None
66+
if self.head is not None:
67+
self.head.prev = None
6068
return temp
6169

62-
def top(self):
70+
def top(self) -> T | None:
6371
"""return the top element of the stack"""
64-
return self.head.data
72+
return self.head.data if self.head is not None else None
6573

66-
def __len__(self):
74+
def __len__(self) -> int:
6775
temp = self.head
6876
count = 0
6977
while temp is not None:
7078
count += 1
7179
temp = temp.next
7280
return count
7381

74-
def is_empty(self):
82+
def is_empty(self) -> bool:
7583
return self.head is None
7684

77-
def print_stack(self):
85+
def print_stack(self) -> None:
7886
print("stack elements are:")
7987
temp = self.head
8088
while temp is not None:
@@ -86,7 +94,7 @@ def print_stack(self):
8694
if __name__ == "__main__":
8795

8896
# Start with the empty stack
89-
stack = Stack()
97+
stack: Stack[int] = Stack()
9098

9199
# Insert 4 at the beginning. So stack becomes 4->None
92100
print("Stack operations using Doubly LinkedList")

0 commit comments

Comments
 (0)