35.python用链表实现堆栈

心不动则不痛 提交于 2020-01-28 12:43:49
class Node:
    def __init__(self):
        self.next=None
        self.data=0
top=None
def isempty():
    if top==None:
        return 1
    else:
        return 0
def push(data):
    global top
    new_node=Node()
    new_node.next=top
    new_node.data=data
    top=new_node
def pop():
    global top
    if isempty()==1:
        print("堆栈已空")
        return  -1
    temp=top.data
    top=top.next
    return temp
while True:
    i=int(input('输入-1停止,输入1压栈,输入0出栈'))
    if i==-1:
        break
    elif i==1:
        data=int(input('输入'))
        push(data)
    else:
        pop()
print('============================================')
while(not isempty()):
    print('堆栈弹出的顺序为:%d'%pop())
print('============================================')

参考图解数据结构书

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!