您好,欢迎访问一九零五行业门户网

Python实现堆栈与队列功能(基于list的append与pop方法)的示例

这篇文章主要介绍了python基于list的append和pop方法实现堆栈与队列功能,结合实例形式分析了python使用list定义及使用队列的相关操作技巧,需要的朋友可以参考下
本文实例讲述了python基于list的append和pop方法实现堆栈与队列功能。分享给大家供大家参考,具体如下:
#coding=utf8 ''''' 堆栈: 堆栈是一个后进先出(lifo)的数据结构。 在栈上"push"元素是个常用术语,意思是把一个对象添加到堆栈中。 删除一个元素,可以把它"pop"出堆栈。 队列: 队列是一种先进先出(fifo)的数据类型。 新的元素通过"入队"的方式添加进队列的末尾, "出对"就是从队列的头部删除。 ''' #创建列表 def creatlist(): initlist=[] try: while true: #从键上输入元素 inputitem=raw_input(u"enter item(输入quit结束输入):") #当输入字符不是quit,把元素加入列表 #当输入字符是quit,结束输入 if inputitem!="quit": initlist.append(inputitem.strip()) else: break #返回输入列表 return initlist except exception,e: print "create list error:",e #删除列表的第一个元素并返回删除元素 def popthefirst(list): try: #判断列表中是否存在元素 #如果存在元素,删除并返回第一个元素 #如果不存在,给出提示信息 if len(list)>0: return list.pop(0) else: print "the list is empty..." except exception,e: print "pop the first item error:",e #删除列表的最后元素并返回删除元素 def popthelast(list): try: #判断列表中是否存在元素 #如果存在元素,删除并返回最后元素 #如果不存在,给出提示信息 if len(list)>0: #pop函数默认删除最后一个元素 return list.pop() else: print "the list is empty..." except exception,e: print "pop the last item error:",e #调用creatlist函数创建表 listone=creatlist() #输出创建表信息 print "the init list :",listone #调用popthefirst函数删除并返回第一个元素 thefirst=popthefirst(listone) #输出当前表的第一个元素 print "the first item of list:",thefirst #调用popthefirst函数删除并返回最后一个元素 thelast=popthelast(listone) #输出当前表的最后一个元素元素 print "the last item of list:",thelast ''''' 这里的listone、thefirst、thelast都是全局变量 如果更改上述语句顺序会获取不到想要的结果。 '''
运行结果:
以上就是python实现堆栈与队列功能(基于list的append与pop方法)的示例的详细内容。
其它类似信息

推荐信息