เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การสร้างเมธอด pop สำหรับ stack

ในแบบฝึกหัดนี้ คุณจะสร้างการทำงานของ pop() สำหรับ stack โดย pop() จะใช้ลบ element ออกจากด้านบนสุดของ stack อีกครั้ง เราจะใช้ attribute size เพื่อทราบจำนวน element ที่อยู่ใน stack

ทบทวน class 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 
แก้ไขและรันโค้ด