-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.py
More file actions
46 lines (29 loc) · 870 Bytes
/
stack.py
File metadata and controls
46 lines (29 loc) · 870 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from typing import TypeVar, Generic
T = TypeVar('T')
class Node(Generic[T]):
def __init__(self, value: T) -> None:
self.value: T = value
self.prev: Node[T] = None
class Stack(Generic[T]):
length: int
head: Node[T] | None
def __init__(self) -> None:
self.length = 0
self.head = None
def push(self, value: T) -> None:
node = Node(value)
self.length += 1
if self.head is None:
self.head = node
return
node.prev = self.head
self.head = node
def pop(self) -> T | None:
if self.head is None:
return None
self.length -= 1
value = self.head.value
self.head = self.head.prev
return value
def peek(self) -> T | None:
return self.head.value if self.head else None