数据结构-01-环形数组
队列queue,特点:先进先出(FIFO)。可以用数组和链表实现。
今天记录下用数组实现队列,要使队列能够循环的使用,则必须使用环形队列实现。
思路:数组中预留一个空元素,以防止数组溢出和计算时取模计算。
定义变量如下:、
rear = 0;(队列底部),当添加元素时+1;
front = 0;(队列头部),当获取元素时+1;
判断队列是否为空:rear == front;
判断队列是否已满:(rear + 1) % maxSize == front;
获取队列元素个数:(rear + maxSize - front) % maxSize;
具体代码如下:
1 namespace Calcs.环形数组 2 { 3 internal class CircleArray 4 { 5 private int maxSize; 6 private int rear; 7 private int front; 8 private int[] array; 9 10 public CircleArray(int maxSize) 11 { 12 this.maxSize = maxSize; 13 this.array = new int[maxSize]; 14 this.rear = 0; 15 this.front = 0; 16 } 17 18 public void AddItem(int item) 19 { 20 if (IsFull()) 21 { 22 Console.WriteLine("队列已满,不能再添加!"); 23 return; 24 } 25 26 array[rear] = item; 27 rear = (rear + 1) % maxSize; 28 } 29 30 31 32 public int GetItem() 33 { 34 if (IsEmpty()) 35 { 36 throw new Exception("队列为空,不能取值!"); 37 } 38 39 int item = array[front]; 40 front = (front + 1) % maxSize; 41 return item; 42 } 43 44 public bool IsFull() 45 { 46 return (rear + 1) % maxSize == front; 47 } 48 49 50 public bool IsEmpty() 51 { 52 return rear == front; 53 } 54 55 public int GetCount() 56 { 57 return (rear + maxSize - front) % maxSize; 58 } 59 60 61 public int GetHeadItem() 62 { 63 if (IsEmpty()) 64 { 65 throw new Exception("队列为空,不能取值!"); 66 } 67 68 return array[front]; 69 70 } 71 72 73 public void ShowArray() 74 { 75 for (int i = front; i < front + GetCount(); i++) 76 { 77 Console.WriteLine($"array[{i % maxSize}]={array[i % maxSize]}"); 78 } 79 } 80 81 82 } 83 }
记录下关键点,以备复习.
分类:
算法和数据结构
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~