首页 > 其他 > 详细

实现栈

时间:2018-05-03 14:02:32      阅读:200      评论:0      收藏:0      [点我收藏+]

简洁版:

class Stack(object):
    def __init__(self):
        self.__list = []

    def push(self, item):
        self.__list.append(item)

    def pop(self):
        return self.__list.pop()

    def peek(self):
        if self.__list:
            return self.__list[-1]
        else:
            return None

    def is_empty(self):
        return self.__list == []

    def size(self):
        return len(self.__list)

注释版:

"""实现栈-->顺序表-->python列表"""


class Stack(object):
    def __init__(self):
        """创建一个空栈"""
        self.__list = []

    def push(self, item):
        """压栈"""
        self.__list.append(item)

    def pop(self):
        """弹栈"""
        return self.__list.pop()

    def peek(self):
        """返回栈顶元素"""
        # 注意: 特殊情况:空列表是不支持切片操作的
        if self.__list:
            # 如果列表不为空
            return self.__list[-1]
        else:
            return None

    def is_empty(self):
        """是否为空栈"""
        return self.__list == []
        # 等价于 return not self.__list

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

实现栈

原文:https://www.cnblogs.com/amou/p/8984836.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!