fix: raise error in peek() function of linkedlist_stack.py, linkedlist_queue.py, linkedlist_deque.py (#754)

* 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 <krahets@163.com>
pull/751/head^2
malone6 1 year ago committed by GitHub
parent e8554975f4
commit a9d70e9e4b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -96,11 +96,15 @@ class LinkedListDeque:
def peek_first(self) -> int: 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: 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]: def to_array(self) -> list[int]:
"""返回数组用于打印""" """返回数组用于打印"""

@ -51,9 +51,8 @@ class LinkedListQueue:
def peek(self) -> int: def peek(self) -> int:
"""访问队首元素""" """访问队首元素"""
if self.size() == 0: if self.is_empty():
print("队列为空") raise IndexError("队列为空")
return False
return self.__front.val return self.__front.val
def to_list(self) -> list[int]: def to_list(self) -> list[int]:

@ -35,16 +35,15 @@ class LinkedListStack:
def pop(self) -> int: def pop(self) -> int:
"""出栈""" """出栈"""
num: int = self.peek() num = self.peek()
self.__peek = self.__peek.next self.__peek = self.__peek.next
self.__size -= 1 self.__size -= 1
return num return num
def peek(self) -> int: def peek(self) -> int:
"""访问栈顶元素""" """访问栈顶元素"""
# 判空处理 if self.is_empty():
if not self.__peek: raise IndexError("栈为空")
return None
return self.__peek.val return self.__peek.val
def to_list(self) -> list[int]: def to_list(self) -> list[int]:

Loading…
Cancel
Save