简述
- front 指向队首元素,rear-1 指向队尾元素
- 队列最大长度:MAXSIZE
- 队列当前长度:count = (rear - front + MAXSIZE) % MAXSIZE
- 队列空:front == rear
- 队列满:(rear + 1) % MAXSIZE == front(**此时队列中元素个数为 MAXSIZE–即有一个空闲元素,具体如下图所示)
- 初始状态下,front = rear = 0
![队列满的两种情况](https://i-blog.csdnimg.cn/blog_migrate/ad3665fffd7fbd673cf35d76b8f5a835.png)
代码:
using System;
interface IQueue<T>
{
int Count{get;}
int GetLength();
bool IsEmpty();
void Clear();
void EnQueue(T element);
T DeQueue();
T Peek();
}
class SeqQueue<T> : IQueue<T>
{
private int MAXSIZE;
private T[] data;
int front;
int rear;
public SeqQueue(int size)
{
MAXSIZE = size;
data = new T[size];
front = 0;
rear = 0;
}
public SeqQueue() : this(10)
{
}
public int Count{get{return (rear - front + MAXSIZE) % MAXSIZE;}}
public int GetLength()
{
return (rear - front + MAXSIZE) % MAXSIZE;
}
public bool IsEmpty()
{
return front == rear;
}
public void Clear()
{
front = -1;
rear = -1;
}
public void EnQueue(T value)
{
if((rear + 1) % MAXSIZE == front)
{Console.WriteLine("SeqQueue is full, can not EnQueue"); return;}
data[rear] = value;
rear =(rear+1) % MAXSIZE;
}
public T DeQueue()
{
T value = default(T);
if(IsEmpty())
{
Console.WriteLine("SeqQueue is Empty, can not DeQueue");
return value;
}
else
{
value = data[front];
front = (front+1) % MAXSIZE;
return value;
}
}
public T Peek()
{
return data[front];
}
}
public class Test
{
public static void Main()
{
IQueue<string> queue = new SeqQueue<string>();
queue.EnQueue("aaa");
queue.EnQueue("bbb");
queue.EnQueue("ccc");
Console.WriteLine("push aaa bbb ccc, queue.Count:{0}", queue.Count);
Console.WriteLine("queue.Peek:{0}", queue.Peek());
while(queue.Count > 0)
{
Console.WriteLine("queue.DeQueue:{0}", queue.DeQueue());
}
}
}
执行结果:
push aaa bbb ccc, queue.Count:3
queue.Peek:aaa
queue.DeQueue:aaa
queue.DeQueue:bbb
queue.DeQueue:ccc