本文实例讲述了Python常见数据结构之栈与队列用法。分享给大家供大家参考,具体如下:
Python常见数据结构之-栈
首先,栈是一种数据结构。具有后进先出特性。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
#栈的实现 class Stack(): def __init__( self ,size): self .stack = [] self .size = size self .top = - 1 def push( self ,content): if self .Full(): print "Stack is Full" else : self .stack.append(content) self .top = self .top + 1 def out( self ): if self .Empty(): print "Stack is Empty" else : self .top - = 1 def Full( self ): if self .top = = self .size - 1 : return True else : return False def Empty( self ): if self .top = = - 1 : print "Stack is Empty" if __name__ = = "__main__" : q = Stack( 7 ) q.Empty() q.push( "hello" ) q.Empty() |
运行结果:
Stack is Empty
Python常见数据结构之-队列
队列是一种先进先出的数据结构。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
#队列的实现 class Queue(): def __init__( self ,size): self .queue = [] self .size = size self .head = - 1 self .tail = - 1 def Empty( self ): if self .head = = self .tail: return True else : return False def Full( self ): if self .tail - self .head = = self .size - 1 : return True else : return False def enQueue( self ,content): if self .Full(): print "Queue is Full" else : self .queue.append(content) self .tail + = 1 def outQueue( self ): if self .Empty(): print "Queue is Empty!" else : self .head + = 1 if __name__ = = "__main__" : q = Queue( 6 ) print q.Empty() # True q.enQueue( "123" ) print q.Empty() #False q.outQueue() |
运行结果:
True
False
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/YANG_Gang2017/article/details/78319527