Triển khai phương thức pop cho stack
Trong bài tập này, bạn sẽ triển khai thao tác pop() cho một stack. pop() được dùng để loại bỏ phần tử ở đỉnh của stack. Một lần nữa, chúng ta sẽ sử dụng thuộc tính size để biết số phần tử trong stack.
Nhắc lại lớp Node():
class Node:
def __init__(self, data):
self.data = data
self.next = None
Bài tập này là một phần của khóa học
Cấu trúc dữ liệu và Thuật toán với Python
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
class Stack:
def __init__(self):
self.top = None
self.size = 0
def pop(self):
# Check if there is a top element
if self.____ is None:
return None
else:
popped_node = self.top
# Decrement the size of the stack
self.size -= ____
# Update the new value for the top node
self.top = self.____
popped_node.next = None
return popped_node.data