如何用两个栈实现一个队列
来源:互联网 发布:淘宝网网上购物流程 编辑:程序博客网 时间:2024/06/05 09:44
How to use two stacks to implement a queue ?
今天看到的有意思的问题题,哇咔咔,简直益智类哇~
"""Code writer : EOFCode date : 2015.02.08Code file : Queue_by_two_stack.pye-mail : jasonleaster@163.comCode description : How to implement a queue by two stack."""class Stack() : S = [] def __init__(self, arg = []): self.S = [len(arg)] + arg def stack_empty(self) : if self.S[0] == 0 : return True else : return False def push(self,x) : self.S[0] += 1 if len(self.S) > self.S[0] : self.S[self.S[0]] = x else : self.S = self.S + [x] return self.S def pop(self) : if self.stack_empty() == True : print "underflow" else : temp = self.S[0] self.S[0] -= 1 return self.S[temp] def show_stack(self) : print "stack status:",self.S[1 : self.S[0] + 1]#---------------------------------------------------------------class Queue() : def __init__(self, argv = []) : self.s_1 = Stack() self.s_2 = Stack() for i in range(0, len(argv)) : self.s_1.push(argv[i]) def is_empty(self) : if self.s_1.stack_empty() is True and \ self.s_2.stack_empty() is True : return True else : return False def enqueue(self, num) : self.s_1.push(num) def dequeue(self) : if self.s_2.stack_empty() is True : while self.s_1.stack_empty() is False : self.s_2.push(self.s_1.pop()) if self.is_empty() is False : return self.s_2.pop()#---------------------------------------------------------------"""Code below this is writed for testing :)"""Q = Queue([1,2,3,4,5])Q.enqueue(100)while Q.is_empty() is False : print Q.dequeue(),
运行结果:
二零一五年摄于排云阁 十字路口的陌生人
0 0
- 如何用两个栈实现一个队列
- 如何用两个栈实现一个队列
- 如何用两个栈实现一个队列
- 如何用两个栈实现一个队列
- 如何用两个栈实现一个队列,以及用两个队列实现一个栈
- 如何用两个栈视线一个队列
- 如何用两个栈形成一个队列
- Java:如何用两个队列实现栈
- 如何用一个栈实现队列?
- 数据结构:栈和列之如何用两个队列实现一个栈?两个栈实现一个队列?
- 如何用两个队列实现一个栈,并分析有关栈操作的运行时间。
- 如何用两个栈实现一个队列(思路)(欢迎提意见)
- 如何用两个栈来实现队列的方法
- 如何用两个栈实现队列的功能
- 如何用两个栈来实现队列的方法
- 如何用两个栈模拟队列操作
- 如何用栈实现队列的功能
- c++ 如何用一个函数实现两个字符串的比较
- 余弦相似度 —— Cosine Similarity
- Android studio调用第三方aidl
- 负载均衡与HTTP加速
- 数据结构-图
- 实践:服务器编写/系统架构/cache
- 如何用两个栈实现一个队列
- 网速变慢深度分析
- 字符串-06. IP地址转换(20)
- HTTP差错分类解析
- 糊涂窗口综合症和Nagle算法
- 算法导论学习-线段树(2)
- maven配置---setting.xml的配置
- io7,io8中关于scrollView在navigationController中的偏移问题
- 机器学习基石笔记4——在何时可以使用机器学习(4)