class StackNode:
def __init__(self,data=None):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
class LinkStack:
def __init__(self):
self.top = None
# 进栈
def Push(self,e):
p=StackNode(e)
p.next=self.top
self.top=p
# 出栈
def Pop(self):
if self.top is None:
raise Exception("栈空")
e=self.top.data
self.top=self.top.next
return e
# 读取栈顶元素
def get_top(self):
if self.top is not None:
return self.top.data
else:
raise Exception("栈空")
# 求长度
def __len__(self):
p=self.top
count=0
while p.next is not None:
p=p.next
count+=1
return count
if __name__ == '__main__':
s=LinkStack()
s.Push(10)
s.Push(11)
s.Push(12)
# print("栈为:",s)
print("栈的长度为:",len(s))
print("此时栈顶元素为:",s.get_top())
StackNode
文章字数:615
阅读时间: 2 分钟
等 人表示很赞
评论