1
1
# A complete working Python program to demonstrate all
2
2
# stack operations using a doubly linked list
3
3
4
+ from __future__ import annotations
4
5
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 ):
7
13
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
10
16
11
17
12
- class Stack :
18
+ class Stack ( Generic [ T ]) :
13
19
"""
14
20
>>> stack = Stack()
15
21
>>> stack.is_empty()
@@ -35,10 +41,10 @@ class Stack:
35
41
2->1->0->
36
42
"""
37
43
38
- def __init__ (self ):
39
- self .head = None
44
+ def __init__ (self ) -> None :
45
+ self .head : Node [ T ] | None = None
40
46
41
- def push (self , data ) :
47
+ def push (self , data : T ) -> None :
42
48
"""add a Node to the stack"""
43
49
if self .head is None :
44
50
self .head = Node (data )
@@ -49,32 +55,34 @@ def push(self, data):
49
55
new_node .prev = None
50
56
self .head = new_node
51
57
52
- def pop (self ):
58
+ def pop (self ) -> T | None :
53
59
"""pop the top element off the stack"""
54
60
if self .head is None :
55
61
return None
56
62
else :
63
+ assert self .head is not None
57
64
temp = self .head .data
58
65
self .head = self .head .next
59
- self .head .prev = None
66
+ if self .head is not None :
67
+ self .head .prev = None
60
68
return temp
61
69
62
- def top (self ):
70
+ def top (self ) -> T | None :
63
71
"""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
65
73
66
- def __len__ (self ):
74
+ def __len__ (self ) -> int :
67
75
temp = self .head
68
76
count = 0
69
77
while temp is not None :
70
78
count += 1
71
79
temp = temp .next
72
80
return count
73
81
74
- def is_empty (self ):
82
+ def is_empty (self ) -> bool :
75
83
return self .head is None
76
84
77
- def print_stack (self ):
85
+ def print_stack (self ) -> None :
78
86
print ("stack elements are:" )
79
87
temp = self .head
80
88
while temp is not None :
@@ -86,7 +94,7 @@ def print_stack(self):
86
94
if __name__ == "__main__" :
87
95
88
96
# Start with the empty stack
89
- stack = Stack ()
97
+ stack : Stack [ int ] = Stack ()
90
98
91
99
# Insert 4 at the beginning. So stack becomes 4->None
92
100
print ("Stack operations using Doubly LinkedList" )
0 commit comments