Modify the exception handling in Java and Python.

This commit is contained in:
krahets
2023-04-23 03:41:39 +08:00
parent 7e59e2c7fb
commit 3590262c7e
14 changed files with 35 additions and 28 deletions

View File

@ -72,12 +72,14 @@ class ArrayDeque:
def peek_first(self) -> int:
"""访问队首元素"""
assert not self.is_empty(), "双向队列为空"
if self.is_empty():
raise IndexError("双向队列为空")
return self.__nums[self.__front]
def peek_last(self) -> int:
"""访问队尾元素"""
assert not self.is_empty(), "双向队列为空"
if self.is_empty():
raise IndexError("双向队列为空")
# 计算尾元素索引
last = self.index(self.__front + self.__size - 1)
return self.__nums[last]

View File

@ -28,9 +28,10 @@ class ArrayQueue:
def push(self, num: int) -> None:
"""入队"""
assert self.__size < self.capacity(), "队列已满"
if self.__size == self.capacity():
raise IndexError("队列已满")
# 计算尾指针,指向队尾索引 + 1
# 通过取余操作,实现 rear 越过数组尾部后回到头部
# 通过取余操作,实现 rear 越过数组尾部后回到头部F
rear: int = (self.__front + self.__size) % self.capacity()
# 将 num 添加至队尾
self.__nums[rear] = num
@ -46,7 +47,8 @@ class ArrayQueue:
def peek(self) -> int:
"""访问队首元素"""
assert not self.is_empty(), "队列为空"
if self.is_empty():
raise IndexError("队列为空")
return self.__nums[self.__front]
def to_list(self) -> list[int]:

View File

@ -26,12 +26,14 @@ class ArrayStack:
def pop(self) -> int:
"""出栈"""
assert not self.is_empty(), "栈为空"
if self.is_empty():
raise IndexError("栈为空")
return self.__stack.pop()
def peek(self) -> int:
"""访问栈顶元素"""
assert not self.is_empty(), "栈为空"
if self.is_empty():
raise IndexError("栈为空")
return self.__stack[-1]
def to_list(self) -> list[int]: