class stack:
def __init__(self):
self.stack=[]
def push(self,element):
self.stack.append(element)
def pop(self):
return self.stack.pop()
def get_top(self):
if len(self)>0:
return self.stack[-1]
else:
return None
a=stack()
a.push(1)
a.push(2)
a.push(3)
print(a.pop())
队列:
class qq:
def __init__(self,size=100):
self.qq=[0 for _ in range(size)]
self.rear=0#队尾
self.front=0#队首
self.size=size
def push(self,element):
self.rear=(self.rear+1)%self.size
self.qq[self.rear]=element
def pop(self):
if not self.is_empty():
self.front=(self.front+1)%self.size
return qq[self.front]
else:
return 0
def is_empty(self):
return self.rear==self.front
def is_full(self):
return (self.rear+1)%self.size==self.front
q=qq(4)
for i in range(4):
q.push(i)
print(q.pop())
队列的内置模块
from collections import deque
#单向队列
q= deque([1,2,3])
q.append(4)#队尾进队
print(q.popleft())#队首出队
#双向队列
q.appendleft(1)#队首进队
print(q.pop())#队尾出队
from collections import deque
#单向队列
q= deque([1,2,3,4,5],5)#长度为5,若在加元素,自动出1
q.append(6)#队尾进队
print(q.popleft())#队首出队
#双向队列
q.appendleft(1)#队首进队
print(q.pop())#队尾出队
下一章:链表