-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.py
More file actions
50 lines (32 loc) · 982 Bytes
/
queue.py
File metadata and controls
50 lines (32 loc) · 982 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
46
47
48
49
from typing import TypeVar, Generic
T = TypeVar('T')
class Node(Generic[T]):
def __init__(self, value: T) -> None:
self.value: T = value
self.next: Node[T] | None = None
class Queue(Generic[T]):
length: int
head: Node[T] | None
tail: Node[T] | None
def __init__(self):
self.head = self.tail = None
self.length = 0
def enqueue(self, value: T) -> None:
node = Node(value)
self.length += 1
if not self.tail:
self.tail = self.head = node
return
self.tail.next = node
self.tail = node
def deque(self) -> T | None:
if not self.head:
return None
self.length -= 1
if self.length == 0:
self.tail = None
value = self.head.value
self.head = self.head.next
return value
def peek(self) -> T | None:
return self.head.value if self.head else None