开始使用免费开始使用

为栈实现 pop 方法

在本练习中,您将为栈实现 pop() 操作。pop() 用于从栈顶移除一个元素。同样,我们将通过 size 属性来表示栈中元素的数量。

回顾 Node() 类:

class Node:
  def __init__(self, data):
    self.data = data
    self.next = None

本练习是课程的一部分

Python 中的数据结构与算法

查看课程

交互式实操练习

通过完成这段示例代码来试试这个练习。

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 
编辑并运行代码