• 数据结构 | Python实现栈的基本操作 | 源码和示例


    1. # Stack class with basic stack operations
    2. class Stack:
    3. def __init__(self):
    4. # Initialize an empty list to store stack elements
    5. self.items = []
    6. def is_empty(self):
    7. # Check if the stack is empty
    8. return len(self.items) == 0
    9. def push(self, item):
    10. # Push (add) an item onto the top of the stack
    11. self.items.append(item)
    12. def pop(self):
    13. if not self.is_empty():
    14. # Pop (remove and return) the item from the top of the stack
    15. return self.items.pop()
    16. else:
    17. # If the stack is empty, return a message indicating so
    18. return "Stack is empty"
    19. def peek(self):
    20. if not self.is_empty():
    21. # Peek at (view) the item on the top of the stack without removing it
    22. return self.items[-1]
    23. else:
    24. # If the stack is empty, return a message indicating so
    25. return "Stack is empty"
    26. def size(self):
    27. # Get the number of elements in the stack
    28. return len(self.items)
    29. def output_stack(self):
    30. # Output the elements of the stack
    31. print("Stack elements:", self.items)
    32. def main():
    33. # Create a new stack
    34. my_stack = Stack()
    35. # Check if the stack is empty
    36. print("Is the stack empty?", my_stack.is_empty())
    37. # Push elements onto the stack
    38. my_stack.push(1)
    39. my_stack.push(2)
    40. my_stack.push(3)
    41. # Output the elements of the stack
    42. my_stack.output_stack()
    43. # Check the size of the stack
    44. print("Stack size:", my_stack.size())
    45. # Peek at the top element of the stack
    46. print("Top element:", my_stack.peek())
    47. # Pop elements from the stack
    48. popped_item = my_stack.pop()
    49. print("Popped item:", popped_item)
    50. # Check the size of the stack after popping
    51. print("Stack size after pop:", my_stack.size())
    52. # Check if the stack is empty again
    53. print("Is the stack empty now?", my_stack.is_empty())
    54. # Output the elements of the stack
    55. my_stack.output_stack()
    56. if __name__ == "__main__":
    57. main()

    结果:

    Is the stack empty? True
    Stack elements: [1, 2, 3]
    Stack size: 3
    Top element: 3
    Popped item: 3
    Stack size after pop: 2
    Is the stack empty now? False
    Stack elements: [1, 2]

  • 相关阅读:
    统计学习方法 隐马尔可夫模型
    【FPGA项目】图像采集及显示(3)总结
    BERT之后,NLP主要预训练模型演变梳理
    JVM诊断及工具笔记(4) 使用visualvm分析JVM堆内存泄漏
    利用XXXXXXXXMIND管理。
    苹果开源高效语言模型 OpenELM;全球首个 AI 基因编辑器开源丨RTE 开发者日报 Vol.192
    【无标题】
    ssm+vue+elementUI 服装定制系统-#毕业设计
    lvs项目
    2024年山东省职业院校技能大赛中职组“网络安全”赛项竞赛试题-B
  • 原文地址:https://blog.csdn.net/L040514/article/details/134013958