一.栈(stack)
1.后进先出,压入(push),弹出(pop)
2.栈顶 S[S.top] 操作,S.top指向最新压入的元素
1 #栈(stack) 2 class Stack: 3 def __init__(self,S=[]): 4 #初始化空栈,设置属性栈顶指针top和栈的列表表示 5 self.top=len(S)-1 6 self.list=S 7 def stack_empty(self): 8 #判断栈空 9 if self.top==-1: 10 return True 11 else: 12 return False 13 def push(self,x): 14 #栈的压入操作 15 self.top+=1#栈顶指针+1 16 self.list.append(x)#把x添加进栈 17 def pop(self): 18 #栈的弹出操作 19 if self.stack_empty(): 20 print("underflow") 21 else: 22 self.top-=1 23 return self.list.pop() 24 def top_element(self): 25 #返回栈顶元素 26 return self.list[S.top] 27 28 A=[15,6,2,9,17,3] 29 S=Stack(A) 30 print(S) 31 print(S.top) 32 print(S.list) 33 print(S.stack_empty()) 34 print(S.top_element()) 35 print('#'*60) 36 S.pop() 37 S.push(100) 38 print(S.list) 39 print(S.top_element()) 40 ------------------------------------------------------ 41 <__main__.Stack object at 0x0102B4D0> 42 5 43 [15, 6, 2, 9, 17, 3] 44 False 45 3 46 ############################################################ 47 [15, 6, 2, 9, 17, 100] 48 False 49 100
二.队列(queue)
1.先进先出,入队(enqueue),出队(dequeue)
2.队头(head)出对 ,队尾(tail)入队
1 #队列 2 class Queue: 3 def __init__(self,Q,head,tail,size): 4 #初始化一个队列,给出头指针,给定总的队的大小size 5 self.list=Q 6 self.head=head 7 self.tail=tail 8 self.size=size 9 10 def enqueue(self,x): 11 #入队操作,判断上溢,改变队尾指针 12 if self.head==self.tail+1 or (self.head==0 and self.tail == self.size-1): 13 return "overflow" 14 self.list.append(x) 15 if self.tail == self.size-1: 16 self.tail=0 17 else: 18 self.tail+=1 19 20 def dequeue(self): 21 #出队操作,判断下溢,改变队头指针 22 if self.head==self.tail: 23 return "underflow" 24 x=self.list[0] 25 self.list.remove(self.list[0]) 26 if self.head==self.size-1: 27 self.head=0 28 else: 29 self.head+=1 30 return x 31 32 A=[15,6,9,8,4] 33 Q = Queue(A,6,10,11) 34 print(Q) 35 print(Q.list) 36 print(Q.head) 37 print(Q.tail) 38 print(Q.size) 39 print('#'*60) 40 Q.enqueue(17) 41 Q.enqueue(3) 42 Q.enqueue(5) 43 print(Q.list) 44 print(Q.head) 45 print(Q.tail) 46 print('#'*60) 47 a=Q.dequeue() 48 print(a) 49 print(Q.list) 50 print(Q.head) 51 print(Q.tail) 52 print('#'*60) 53 b=Q.dequeue() 54 print(b) 55 print(Q.list) 56 print(Q.head) 57 print(Q.tail) 58 ---------------------------------------------------------------- 59 [15, 6, 9, 8, 4] 60 6 61 10 62 11 63 ############################################################ 64 [15, 6, 9, 8, 4, 17, 3, 5] 65 6 66 2 67 ############################################################ 68 15 69 [6, 9, 8, 4, 17, 3, 5] 70 7 71 2 72 ############################################################ 73 6 74 [9, 8, 4, 17, 3, 5] 75 8 76 2