06 栈

06 栈

# encoding: utf=8

class Stack(object):
    """栈"""

    def __init__(self):
        self._list = []

    def is_empty(self):
        """判断栈是否为空"""
        return len(self._list) == 0

    def size(self):
        """返回栈的元素个数"""
        return len(self._list)

    def push(self, item):
        """添加一个新元素到栈顶"""

        # 列表尾部添加元素 复杂度O(1)
        self._list.append(item)

    def pop(self):
        """弹出栈顶元素"""

        return self._list.pop()

    def peek(self):
        """返回栈顶元素"""

        # 判断是否为空
        if self._list:
            return self._list[-1]
        else:
            return None

    

if __name__ == '__main__':
    s = Stack()
    s.push(1)
    s.push(2)
    s.push(3)
    s.push(4)
    print(s.pop())
    print(s.pop())
    print(s.pop())
    print(s.pop())

# 4 3 2 1

猜你喜欢

转载自blog.csdn.net/qq_41089707/article/details/89301478