ALL · 2020年4月6日

简单链栈 Python

class Node:
    def __init__(self,data,next):
        self.data=data
        self.next=next
class LinkStack:
    def __init__(self):
        self.top=Node(None,None)

    def IsEmpty(self):
        if self.top.next==None:
            print('当前状态:空栈')
            return True
        else:return False

    def PushStack(self,d):
        for i in d:
            self.top=Node(i,self.top)
            print(i,end=' ')
            # print('mk:',self.top.data,self.top,self.top.next)
        print()

    def PopStack(self):
        if self.IsEmpty():
            return
        else:
            print(self.top.data,self.top)
            self.top=self.top.next

    def GetTop(self):
        if self.IsEmpty():
            return
        else:
            print('当前状态:顶栈值为',self.top.data,self.top)
            return self.top.data



print('当前状态:初始化链栈')
LS=LinkStack()
LS.IsEmpty()
print('当前状态:依次进栈 ',end=' ')
LS.PushStack([2,4,6])
LS.GetTop()
print('当前状态:依次出栈:')
LS.PopStack()
LS.PopStack()
LS.PopStack()