本文共 2178 字,大约阅读时间需要 7 分钟。
interface IQueue{ int GetLength(); void Clear(); void EnQueue(T elem); void Dequeue(); T Peek(); bool IsEmepty(); }
class Queue: IQueue { private T[] data; private int count;//元素个数 private int maxSize; //数组最大容量 private int front;//对头下标 private int rear;// 队尾下标
public Queue(int maxSize) { this.maxSize = maxSize; data=new T[maxSize]; //开内存分配空间 front = rear = 0; count =0; } public void Clear() { front = rear = 0; data = null; }
//出队 public void Dequeue() { //判断队是否为空 //移除数据 //frorn++ //count if (rear==front) { throw new Exception("队为空无法删除"); } front=(front+1)%maxSize; count--; }
//入队 public void EnQueue(T elem) { //判断是否已满 //加入数据 //rear后移 //count++ if ((rear + 1) % maxSize == front) { throw new Exception("队满无法存储数据"); } data[rear] = elem; rear = (rear + 1) % maxSize; count++; }
public int GetLength() { return (rear - front + maxSize) % maxSize; }
public bool IsEmepty() { return front == rear; }
public T Peek() { if (rear == front) { throw new Exception("队为空无法获取数据"); } return data[front]; } }
class Program { static void Main(string[] args) { Queue sum=new Queue (4); Console.WriteLine(sum.IsEmepty()); Console.WriteLine(sum.GetLength()); sum.EnQueue(100); sum.EnQueue(200); sum.EnQueue(300); sum.EnQueue(400); Console.WriteLine(sum.IsEmepty()); sum.Dequeue(); Console.WriteLine(sum.GetLength()); Console.WriteLine(sum.Peek()); Console.ReadKey(); } }
转载地址:http://adrxo.baihongyu.com/