Python可以实现栈的结构吗
栈(stack)又名堆栈,它是一种运算受限的线性表。在Python中可使用列表进行实现。
什么是栈?
栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。
如何实现?
在Python中使用列表来实现:
#!/usr/bin/envpython #定义一个列表来模拟栈 stack=[] #进栈,调用列表的append()函数加到列表的末尾,strip()没有参数是去掉首尾的空格 defpushit(): stack.append(raw_input('Enternewstring:').strip()) #出栈,用到了pop()函数 defpopit(): iflen(stack)==0: print'Cannotpopfromanemptystack!' else: print'Removed[',stack.pop(),']' #编历栈 defviewstack(): printstack #CMDs是字典的使用 CMDs={'u':pushit,'o':popit,'v':viewstack} #pr为提示字符 defshowmenu(): pr=""" p(U)sh p(O)p (V)iew (Q)uit Enterchoice:""" whileTrue: whileTrue: try: #先用strip()去掉空格,再把第一个字符转换成小写的 choice=raw_input(pr).strip()[0].lower() except(EOFError,KeyboardInterrupt,IndexError): choice='q' print'\nYoupicked:[%s]'%choice ifchoicenotin'uovq': print'Invalidoption,tryagain' else: break #CMDs[]根据输入的choice从字典中对应相应的value,比如说输入u,从字典中得到value为pushit,执行pushit()进栈操作 ifchoice=='q': break CMDs[choice]() #判断是否是从本文件进入,而不是被调用 if__name__=='__main__': showmenu()
实例内容扩展:
#-*-coding:utf-8-*- #__author__:kusy #__content__:文件说明 #__date__:2018/9/3017:28 classMyStack(object): def__init__(self): self.stack_list=[] self.count=0 #创建一个栈 defcreate_stack(self): returnself.stack_list #栈中添加值 defpush(self,value): self.stack_list.insert(0,value) self.count+=1 #返回栈顶元素值 defpeek(self): ifself.count: returnself.stack_list[0] #删除栈顶元素 defpop(self): self.stack_list.pop(0) self.count-=1 #返回栈是否为空 defis_empty(self): returnself.count==0 #打印栈内容 defprint_all(self): forslinself.stack_list: print(sl) if__name__=='__main__': ms=MyStack() ms.create_stack() ms.push(1) ms.push(2) ms.push(3) print('栈元素:') ms.print_all() print('栈顶元素:',ms.peek()) ms.pop() print('栈顶元素删除后:') ms.print_all() print('栈是否为空:','是'ifms.is_empty()else'否') print('---继续删除元素') ms.pop() print('---继续删除元素') ms.pop() print('栈是否为空:','是'ifms.is_empty()else'否')
运行结果如下
C:\Users\suneee\AppData\Local\Programs\Python\Python36\python.exeE:/wangjz/PyWorkSpace/LearnPython/PY0929/stack.py 栈元素: 3 2 1 栈顶元素:3 栈顶元素删除后: 2 1 栈是否为空:否 ---继续删除元素 ---继续删除元素 栈是否为空:是 Processfinishedwithexitcode0
到此这篇关于Python可以实现栈的结构吗的文章就介绍到这了,更多相关Python实现栈的结构的条件内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!