python实现数据结构-队列

注:本文档主要是学习《Python核心编程(第二版)》时的练习题。

队列是一种"先进先出"的数据结构(FIFO),是一种操作受限的线性结构,先进队列的成员先出队列。示意图如下:

代码如下:

 1 #!/usr/bin/env python
 2 
 3 queue = []
 4 
 5 def enQ():
 6     queue.append(raw_input('Enter new string: ').strip())
 7 
 8 def deQ():
 9     if len(queue) == 0:
10         print 'Cannot pop from an empty queue!'
11     else:
12         print 'Remove [', queue.pop(0), ']'
13 
14 def viewQ():
15     print queue
16 
17 CMDs = {'e':enQ, 'd':deQ, 'v':viewQ}
18 
19 def showmenu():
20     pr = """
21 (E)nqueue
22 (D)equeue
23 (V)iew
24 (Q)uit
25 
26 Enter choice: """
27 
28     while True:
29         try:
30             choice = raw_input(pr).strip()[0].lower()
31         except (EOFError, keyboardInterrupt, IndexError):
32             choice = 'q'
33 
34         print '\nYour picked: [%s]' % choice
35         
36         if choice == 'q':
37             break
38         elif choice not in 'dev':
39             print 'Invalid option, try again'
40         else:
41             CMDs[choice]()
42 
43 if __name__ == '__main__':
44     showmenu()

测试现象:

 1 [root@localhost python]# python queue.py    
 2 
 3 (E)nqueue
 4 (D)equeue
 5 (V)iew
 6 (Q)uit
 7 
 8 Enter choice: e
 9 
10 Your picked: [e]
11 Enter new string: abcd
12 
13 (E)nqueue
14 (D)equeue
15 (V)iew
16 (Q)uit
17 
18 Enter choice: e
19 
20 Your picked: [e]
21 Enter new string: 1234
22 
23 (E)nqueue
24 (D)equeue
25 (V)iew
26 (Q)uit
27 
28 Enter choice: v
29 
30 Your picked: [v]
31 ['abcd', '1234']
32 
33 (E)nqueue
34 (D)equeue
35 (V)iew
36 (Q)uit
37 
38 Enter choice: d
39 
40 Your picked: [d]
41 Remove [ abcd ]
42 
43 (E)nqueue
44 (D)equeue
45 (V)iew
46 (Q)uit
47 
48 Enter choice: v
49 
50 Your picked: [v]
51 ['1234']
52 
53 (E)nqueue
54 (D)equeue
55 (V)iew
56 (Q)uit

 

posted @ 2019-12-03 22:48  zhengcixi  阅读(215)  评论(0编辑  收藏  举报
回到顶部