数据结构-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 }

记录下关键点,以备复习.
复制代码

posted on   潇潇@暮雨  阅读(456)  评论(0编辑  收藏  举报

(评论功能已被禁用)
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示