插入操作只能在尾部进行,删除操作只能在表头进行
队列先进先出
顺序队列的多次入队和出队操作会造成有存储空间却不能进行入队操作的‘假溢出’
顺序队列的存储单元没有重复使用机制
解决方案:将顺序队列的首尾相连,形成循环顺序队列
循环顺序队列需要少利用一个存储单元
class SqQueue: def __init__(self,maxSize): self.maxSize = maxSize # 队列最大存储个数 self.queueElem = [None] * self.maxSize # 队列的存储空间 self.front = 0 # 指向队首元素 self.rear = 0 # 指向队尾元素的下一个存储单元 def clear(self): """将队列置空""" self.front = 0 self.rear = 0 def isEmpty(self): """判断队列是否为空""" return self.rear == self.front def length(self): """返回队列的数据元素个数""" return self.rear - self.front def peek(self): """返回队首元素""" if self.isEmpty(): return None else: return self.queueElem[self.front] def offer(self,x): """插入队尾""" if self.rear == self.maxSize: return '满' self.queueElem[self.rear] = x self.rear += 1 def poll(self): """将队首元素删除并返回其值""" if self.isEmpty(): return None p = self.queueElem[self.front] self.front += 1 return p def display(self): """输出队列中的所有元素""" for i in range(self.front,self.rear): print(self.queueElem[i])
链队列用单链表实现,不需要设置头节点
class Node: def __init__(self,data = None,next = None): self.data = data self.next = next class LinkQueue: def __init__(self): self.front = None # 队首指针 self.rear = None # 队尾指针 def clear(self): """将队列置空""" self.front = None self.rear = None def isEmpty(self): """判断队列是为为空""" return self.front is None def length(self): """返回队列长度""" p = self.front count = 0 while p is not None: p = p.next count += 1 return count def peek(self): """返回队首元素""" if self.isEmpty(): return None else: return self.front.data def offer(self,x): """插入队尾""" s = Node(x,None) if not self.isEmpty(): self.rear.next = s else: self.front = s self.rear = s def poll(self): """删除队首元素""" if self.isEmpty(): return None p = self.front self.front = self.front.next if p == self.rear: self.rear = None return p.data def display(self): """输出队列中的元素""" p = self.front while p is not None: print(p.data) p = p.next
优先级队列是在普通队列的基础上将队列中的数据元素按照关键字的值进行有序排列
优先级队列在队首进行删除操作,但为了保证队列的优先级顺序,插入操作不一定在队尾进行,而是按照优先级插入到队列的合适位置
优先级队列通常采用链式存储结构
class PriorityNode: def __init__(self,data=None,priority = None,next = None): self.data = data # 节点的数据域 self.priority = priority # 节点的优先级 self.next = next
《数据结构(Python版)》作者:吕云翔、郭颖美、孟爻