复习实现栈的基本操作

 1 class Stack(object):
 2     '''创建一个栈'''
 3     def __init__(self):
 4         self.__lst = []
 5         # 将列表设置为私有,不让外界进行访问
 6 
 7     def add(self,data):
 8         '''在尾部添加元素'''
 9         self.__lst.append(data)
10 
11 
12     def pop(self):
13         '''在尾部取出元素'''
14         return self.__lst.pop()
15         # pop 删除最后一个对象,并返回值
16 
17     def peek(self):
18         '''返回栈顶元素'''
19         if self.__lst != []:
20             # 如果不为空
21             return self.__lst[-1]
22             # 返回最后一个元素(后进先出)
23         else:
24             # 栈为空
25             return None 
26 
27     def is_empty(self):
28         '''判断链表是否为空'''
29         return self.__lst == []
30         # 不要直接返回 self.__lst 会导致外部得到私有成员
31 
32     def size(self):
33         '''返回栈的元素个数'''
34         return len(self.__lst)
35         # self.__lst 为列表对象,使用 len 获取长度

2020-04-15

猜你喜欢

转载自www.cnblogs.com/hany-postq473111315/p/12705117.html