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

# Stack class with basic stack operations
class Stack:
    def __init__(self):
        # Initialize an empty list to store stack elements
        self.items = []

    def is_empty(self):
        # Check if the stack is empty
        return len(self.items) == 0

    def push(self, item):
        # Push (add) an item onto the top of the stack
        self.items.append(item)

    def pop(self):
        if not self.is_empty():
            # Pop (remove and return) the item from the top of the stack
            return self.items.pop()
        else:
            # If the stack is empty, return a message indicating so
            return "Stack is empty"

    def peek(self):
        if not self.is_empty():
            # Peek at (view) the item on the top of the stack without removing it
            return self.items[-1]
        else:
            # If the stack is empty, return a message indicating so
            return "Stack is empty"

    def size(self):
        # Get the number of elements in the stack
        return len(self.items)

    def output_stack(self):
        # Output the elements of the stack
        print("Stack elements:", self.items)

def main():
    # Create a new stack
    my_stack = Stack()

    # Check if the stack is empty
    print("Is the stack empty?", my_stack.is_empty())

    # Push elements onto the stack
    my_stack.push(1)
    my_stack.push(2)
    my_stack.push(3)

    # Output the elements of the stack
    my_stack.output_stack()

    # Check the size of the stack
    print("Stack size:", my_stack.size())

    # Peek at the top element of the stack
    print("Top element:", my_stack.peek())

    # Pop elements from the stack
    popped_item = my_stack.pop()
    print("Popped item:", popped_item)

    # Check the size of the stack after popping
    print("Stack size after pop:", my_stack.size())

    # Check if the stack is empty again
    print("Is the stack empty now?", my_stack.is_empty())

    # Output the elements of the stack
    my_stack.output_stack()
    
if __name__ == "__main__":
    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]

你可能感兴趣的:(数据结构,力扣,1024程序员节,数据结构,开发语言,python)