From a9d70e9e4bda789377a188cf502055d2b0c4be57 Mon Sep 17 00:00:00 2001 From: malone6 Date: Thu, 14 Sep 2023 01:22:53 +0800 Subject: [PATCH] fix: raise error in peek() function of linkedlist_stack.py, linkedlist_queue.py, linkedlist_deque.py (#754) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: linkedlist_stack.py 中的peek方法需要判空raise Error 栈空的时候不能再 peek() 。另外由于 pop() 复用了 peek() ,栈空时返回的 None 会传递到 pop() 中的 num ,导致后续的继续执行 self.peek.next 报错等后续问题 * Update linkedlist_stack.py * Update linkedlist_queue.py * Update linkedlist_deque.py --------- Co-authored-by: Yudong Jin --- codes/python/chapter_stack_and_queue/linkedlist_deque.py | 8 ++++++-- codes/python/chapter_stack_and_queue/linkedlist_queue.py | 5 ++--- codes/python/chapter_stack_and_queue/linkedlist_stack.py | 7 +++---- 3 files changed, 11 insertions(+), 9 deletions(-) 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]: