python数据结构与算法——队列
2015-07-31 16:28
288 查看
队列结构可以使用数组来模拟,只需要设定头和尾的两个标记
参考自《啊哈》
具体使用方法与注意事项,下面不同的实现方式也是同样的道理:
我们也可以自己实现队列类型:
python提供了内置的数据结构,在collections模块中
参考自《啊哈》
# 按书中的代码会出现索引越界的问题(书中申请了超量的空间) # 尝试令tai初始为len(q)-1则不会出错但少了最后一位 # 通过异常处理,捕获出界异常则直接跳出循环 def queue_demo1(q): newq = [] head = 0 tail = len(q) # 记录队列最后一位 while head < tail : newq.append(q[head]) head += 1 try: q.append(q[head]) except IndexError: break head += 1 tail += 1 return newq
具体使用方法与注意事项,下面不同的实现方式也是同样的道理:
if __name__=="__main__": # 注意,往list尾部以外的插入insert和删除del操作都是相当耗费时间的 # 最好只用append或extend q = list("631758924") # 分离字符串序列 newq = queue_demo(q) print newq >>> ['6', '1', '5', '9', '4', '7', '2', '8', '3']
我们也可以自己实现队列类型:
# ======= 手动实现队列类型 ======= # 队列节点元素 class Node: def __init__(self,data,next=None): self.data = data self.next = next # 简单的FIFO队列类别 class Queue: def __init__(self): self.head = None self.tail = None self.count = 0 def append(self,data): if self.head == None: self.head = Node(data) self.tail = self.head else: self.tail.next = Node(data) self.tail = self.tail.next self.count += 1 def pop(self): if self.head == None: raise "Error: head==None" data = self.head.data self.head = self.head.next self.count -= 1 return data # 从新实现上面的算法 def queue_demo2(q): queue = Queue() for item in q: # 初始化队列 queue.append(item) newq = [] while queue.count > 0: newq.append(queue.pop()) # 记录删除的元素 if queue.count==0: break else: temp = queue.pop() # 从新入队的元素 queue.append(temp) return newq
python提供了内置的数据结构,在collections模块中
# 使用python内置对象 # deque: 双端队列,可以快速的从两侧追加和插入的对象 # 注意 list.pop(0) 也可以弹出首元素,但实际上很耗时间 def queue_demo3(q): from collections import deque # 好赞,突然发现,自己写的方法和内置对象名字一模一样,代码完全不用改 # 上面的我也是猜的... queue = deque() for item in q: # 初始化队列 queue.append(item) newq = [] while queue.count > 0: newq.append(queue.pop()) # 记录删除的元素 if queue.count==0: break else: temp = queue.pop() # 从新入队的元素 queue.append(temp) return newq
相关文章推荐
- 【自考】 数据结构
- python数据结构与算法——链表
- python数据结构与算法——快速排序
- (转)hashmap hashtable 的区别 Hash table 内部的数据结构
- python数据结构与算法——桶排序
- python数据结构与算法——冒泡排序
- python数据结构与算法
- 数据结构上机实验之二分查找 SDUT
- [数据结构] Set的基本用法
- 算法和数据结构
- random_queue:支持push, popRamdom的数据结构
- 数据结构之二叉树排序(转载http://www.cnblogs.com/mcgrady/p/3280624.html)
- 魔术师发牌问题(数据结构)
- 数据结构二:企业级线性链表存储底层封装
- 数据结构---单链表(3)
- 数据结构学习--树(一)
- 数据结构学习--树(一)
- 数据结构实验:哈希表 SDUT
- 数据结构之红黑树(三)——删除操作
- 数据结构之红黑树(三)——删除操作