标签:数据结构 color var pre 队列 string stat out span
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 5 namespace 数据结构 6 { 7 public class CircleQueue<T> 8 { 9 //队列最大容量 10 private int maxSize; 11 //队列头 12 private int front; 13 //队列尾 14 private int rear; 15 //队列数组 16 private T[] arrayQueue; 17 //队列尾下一位置,如果和头部重合说明队列已满 18 //所以队列尾部会空一个位置,这样判断队列是否为空好处理一些 19 public bool IsFull { get => (rear + 1) % maxSize == front; } 20 //头尾同时指向同一位置为空 21 public bool IsEmpty { get => front == rear; } 22 //队列剩余数据 23 public int Size { get => (maxSize + rear - front) % maxSize; } 24 25 public CircleQueue(int maxSize = 1) 26 { 27 //由于队列留空了一格,所以最大值要加一 28 this.maxSize = maxSize + 1; 29 arrayQueue = new T[this.maxSize]; 30 //指向队列头 31 this.front = 0; 32 //指向队列尾的下一个位置,也就三队列头部 33 this.rear = 0; 34 } 35 //入队 36 public bool AddQueue(T item) 37 { 38 if (IsFull) 39 { 40 Console.WriteLine("队列已满..."); 41 return false; 42 } 43 arrayQueue[rear] = item; 44 //尾指向下一位置 45 rear = (rear + 1) % this.maxSize; 46 return true; 47 } 48 //出队 49 public T GetQueue() 50 { 51 if (IsEmpty) 52 { 53 throw new IndexOutOfRangeException("队列为空..."); 54 55 } 56 //头指向下一位置 57 var val = arrayQueue[front]; 58 front = (front + 1) % this.maxSize; 59 return val; 60 } 61 } 62 public class CircleQueueGenericDemo 63 { 64 static void Main(string[] args) 65 { 66 //初始化队列 67 var queue = new CircleQueue<string>(9); 68 Console.WriteLine($"泛型当前队列长度为{queue.Size}"); 69 Console.WriteLine("向长度为9的入队10个字符串\n"); 70 for (int i = 1; i <= 10; i++) 71 { 72 73 if (queue.IsFull) 74 { 75 Console.Write("队列已满“10string”入队失败,"); 76 break; 77 } 78 if (queue.AddQueue($"string{i}")) 79 { 80 Console.Write($"string{i}\t"); 81 } 82 83 } 84 Console.WriteLine($"当前队列长度为{queue.Size}\t"); 85 86 87 Console.WriteLine("出队5个字符串...\n"); 88 for (int i = 1; i <= 5; i++) 89 { 90 91 Console.Write($"{queue.GetQueue()}\t"); 92 93 } 94 Console.WriteLine($"当前队列长度为{queue.Size}\n"); 95 } 96 } 97 }
标签:数据结构 color var pre 队列 string stat out span
原文地址:https://www.cnblogs.com/xiaojvhuang/p/12683475.html