码迷,mamicode.com
首页 > 其他好文 > 详细

实现栈

时间:2018-05-03 14:18:53      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:ret   情况   特殊情况   切片   列表   实现   append   操作   list   

简洁版:

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)

实现栈

标签:ret   情况   特殊情况   切片   列表   实现   append   操作   list   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!