diff --git a/codes/python/chapter_stack_and_queue/linkedlist_deque.py b/codes/python/chapter_stack_and_queue/linkedlist_deque.py index aacc6928b..172034b1e 100644 --- a/codes/python/chapter_stack_and_queue/linkedlist_deque.py +++ b/codes/python/chapter_stack_and_queue/linkedlist_deque.py @@ -96,11 +96,15 @@ class LinkedListDeque: def peek_first(self) -> int: """访问队首元素""" - return None if self.is_empty() else self.front.val + if self.is_empty(): + raise IndexError("双向队列为空") + return self.front.val def peek_last(self) -> int: """访问队尾元素""" - return None if self.is_empty() else self.rear.val + if self.is_empty(): + raise IndexError("双向队列为空") + return self.rear.val def to_array(self) -> list[int]: """返回数组用于打印""" diff --git a/codes/python/chapter_stack_and_queue/linkedlist_queue.py b/codes/python/chapter_stack_and_queue/linkedlist_queue.py index 269d03c15..d08abed1b 100644 --- a/codes/python/chapter_stack_and_queue/linkedlist_queue.py +++ b/codes/python/chapter_stack_and_queue/linkedlist_queue.py @@ -51,9 +51,8 @@ class LinkedListQueue: def peek(self) -> int: """访问队首元素""" - if self.size() == 0: - print("队列为空") - return False + if self.is_empty(): + raise IndexError("队列为空") return self.__front.val def to_list(self) -> list[int]: diff --git a/codes/python/chapter_stack_and_queue/linkedlist_stack.py b/codes/python/chapter_stack_and_queue/linkedlist_stack.py index e7f1ba46e..271770a7a 100644 --- a/codes/python/chapter_stack_and_queue/linkedlist_stack.py +++ b/codes/python/chapter_stack_and_queue/linkedlist_stack.py @@ -35,16 +35,15 @@ class LinkedListStack: def pop(self) -> int: """出栈""" - num: int = self.peek() + num = self.peek() self.__peek = self.__peek.next self.__size -= 1 return num def peek(self) -> int: """访问栈顶元素""" - # 判空处理 - if not self.__peek: - return None + if self.is_empty(): + raise IndexError("栈为空") return self.__peek.val def to_list(self) -> list[int]: