码迷,mamicode.com
首页 > 编程语言 > 详细

python数据结构与算法——队列

时间:2015-07-31 17:42:34      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

队列结构可以使用数组来模拟,只需要设定头和尾的两个标记

参考自《啊哈》

 1 # 按书中的代码会出现索引越界的问题(书中申请了超量的空间)
 2 # 尝试令tai初始为len(q)-1则不会出错但少了最后一位
 3 # 通过异常处理,捕获出界异常则直接跳出循环
 4 def queue_demo1(q):
 5     newq = []
 6     head = 0
 7     tail = len(q)                   # 记录队列最后一位
 8     
 9     while head < tail :
10         newq.append(q[head])
11         head += 1
12         try:
13             q.append(q[head])
14         except IndexError:          
15             break                   
16         head += 1
17         tail += 1
18         
19     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]

 

我们也可以自己实现队列类型:

 1 # ======= 手动实现队列类型 =======
 2 # 队列节点元素
 3 class Node:
 4     def __init__(self,data,next=None):
 5         self.data = data
 6         self.next = next
 7 
 8 # 简单的FIFO队列类别
 9 class Queue:
10     def __init__(self):
11         self.head = None
12         self.tail = None
13         self.count = 0
14         
15     def append(self,data):
16         if self.head == None:
17            self.head = Node(data)
18            self.tail = self.head
19         else:
20             self.tail.next = Node(data)
21             self.tail = self.tail.next
22         self.count += 1
23     
24     def pop(self):
25         if self.head == None:
26             raise "Error: head==None"
27         data = self.head.data
28         self.head = self.head.next
29         self.count -= 1
30         return data
31 
32 # 从新实现上面的算法
33 def queue_demo2(q):
34     
35     queue = Queue()
36     for item in q:                  # 初始化队列
37         queue.append(item)
38 
39     newq = []
40     while queue.count > 0:
41         newq.append(queue.pop())    # 记录删除的元素
42         if queue.count==0:
43             break
44         else:
45             temp = queue.pop()      # 从新入队的元素
46             queue.append(temp)
47     
48     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数据结构与算法——队列

标签:

原文地址:http://www.cnblogs.com/hanahimi/p/4692505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!