类名有所修改,此外还使用了typing库中的Any和Optional这两个类来注释返回值类型。from typing import Any, Optional
class _Node:
"""节点类"""
def __init__(self, v: Any) -> None:
self.__value = v
self.__next = None
def get_value(self) -> Any:
"""获取节点保存的值"""
return self.__value
def get_next(self) -> Optional['_Node']:
"""获取下一个节点"""
return self.__next
def set_next(self, n: Optional['_Node']) -> None:
"""设置下一个节点"""
self.__next = n
class QueueError(Exception):
"""自定义队列异常"""
def __init__(self, msg: str) -> None:
"""使用提示信息实例化一个队列异常对象"""
self.val = msg
def __str__(self) -> str:
return self.val
class MyQueue:
"""自定义队列"""
def __init__(self) -> None:
"""实例化自定义队列,使用队首、队尾、长度三个属性记录队列信息"""
self.__head: Optional[_Node] = None # 队首,_Node类型或者为None
self.__tail: Optional[_Node] = None # 队尾,_Node类型或者为None
self.__len: int = 0 # 队列长度
def push(self, x: int) -> None:
"""将x添加到队列末尾"""
node = _Node(x)
if self.__len <= 0:
self.__head = self.__tail = node
else:
self.__tail.set_next(node)
self.__tail = node
self.__len += 1
def pop(self) -> int:
"""从队列开头移除并返回元素"""
if self.__len > 0:
node = self.__head
self.__head = node.get_next()
self.__len -= 1
return node.get_value()
raise QueueError('队列为空')
def peek(self) -> Optional[int]:
"""查看队列开头的元素,如果队列为空则返回None"""
if self.__len <= 0:
return self.__head.get_value()
return None
def empty(self) -> bool:
"""返回队列是否为空"""
return self.__len == 0
if __name__ == '__main__':
q = MyQueue()
for i in range(5):
q.push(i)
print(q.empty())
for i in range(5):
print(q.pop())
q.pop() # 抛出异常
|