• 数据结构 | 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]

  • 相关阅读:
    某电商网站的数据库设计(8)——创建花费信息查询视图
    猿创征文|Vue源码分析(Render渲染函数)
    vue3集成jsoneditor
    Java(六)——常用类Math类
    移动端APP测试-如何指定测试策略、测试标准?
    Win11系统设置闪退的解决方案
    解决 react 项目启动端口冲突
    ATECLOUD智能云测试平台-测试测量/仪器程控/工业控制/上位机开发软件
    mysql 中的锁
    什么是RPC?RPC 和 HTTP 对比?RPC有什么缺点?市面上常用的RPC框架?
  • 原文地址:https://blog.csdn.net/L040514/article/details/134013958