線性迴圈佇列
阿新 • • 發佈:2018-11-24
簡述
- front 指向隊首元素,rear-1 指向隊尾元素
- 佇列最大長度:MAXSIZE
- 隊列當前長度:count = (rear - front + MAXSIZE) % MAXSIZE
- 佇列空:front == rear
- 佇列滿:(rear + 1) % MAXSIZE == front(**此時佇列中元素個數為 MAXSIZE–即有一個空閒元素,具體如下圖所示)
- 初始狀態下,front = rear = 0
程式碼:
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;//data[front+1] is hear element
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;}
//loop, so EnQueue at end is to EnQueue at start
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];
//loop
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