欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

Python数据结构之环形队列

时间:2023-05-31
Python数据结构之环形队列 环形队列:主要解决假溢出现象;公式: rear = front = -1
添加数据 rear = (rear+1) % MAX_SIZE
删除数据 front = (front+1) % MAX_SIZE
判断空: rear == front
判断满 : (rear+1) % MAX_SIZE = front
判断数据个数: (rear - front + MAX_SIZE)%MAX_SIZE 代码 加入数据

def enqueue(name): global rear global front rear = (rear + 1) % MAX_SIZE if rear != front: data_arr[rear] = name else: print("队伍已经为满!")

删除数据

def dequeue(): global front front = (front + 1) % MAX_SIZE if rear != front: find_data = data_arr[front] data_arr[front] = None return find_data else: print("队列以空了!") return None

判断空和判断满

def is_empty(): if rear == front: return True else: return Falsedef is_full(): if (rear + 1) % MAX_SIZE == front: return True else: return False

总价:全部代码

front = rear = -1MAX_SIZE = 6data_arr = [None] * MAX_SIZEdef enqueue(name): global rear global front rear = (rear + 1) % MAX_SIZE if rear != front: data_arr[rear] = name else: print("队伍已经为满!")def dequeue(): global front front = (front + 1) % MAX_SIZE if rear != front: find_data = data_arr[front] data_arr[front] = None return find_data else: print("队列以空了!") return Nonedef is_empty(): if rear == front: return True else: return Falsedef is_full(): if (rear + 1) % MAX_SIZE == front: return True else: return Falseif __name__ == '__main__': enqueue("dog") enqueue("dog") enqueue("dog") enqueue("dog") enqueue("dog") print(data_arr) dequeue() print(data_arr)

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。