class LNode:
"""节点的类"""
def __init__(self,x):
self.data = x
self.next = None
class MyStack:
"""用链表实现栈"""
def __init__(self):
self.data = None
self.next = None
# 判断栈是否为空
def isEmpty(self):
return self.next == None
#获取栈中元素个数
def size(self):
s = 0
p = self.next
while p != None:
p = p.next
s += 1
return s
#取得栈顶元素
def top(self):
if self.next != None:
return self.next.data
else:
print("栈已经为空,无法提取元素")
return None
def pop(self):
if self.next != None:
tmp = self.next
self.next = self.next.next
print("弹栈成功")
return tmp.data
else:
print("栈已经空了,无法弹出")
return None
#把e压入栈顶
def push(self, e):
p = LNode(e)
p.next = self.next
self.next = p
#测试栈的使用
if __name__ == "__main__":
s = MyStack()
s.push(4)
s.push(5)
print("栈顶元素为:%s" % s.top())
print("栈的长度为:%s" % s.size())
s.pop()
print("栈顶元素为:%s" % s.top())
print("栈的长度为:%s" % s.size())
s.pop()
print("栈顶元素为:%s" % s.top())
print("栈的长度为:%s" % s.size())
python用单链表实现栈
最新推荐文章于 2022-11-24 13:32:41 发布