35.python用鏈表實現堆棧

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('============================================')

參考圖解數據結構書

發佈了37 篇原創文章 · 獲贊 28 · 訪問量 2046
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章