wingman007

Queue<T>

May 18th, 2015
515
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.60 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace World2
  8. {
  9.     class Queue<T>
  10.     {
  11.         private const int CAPACITY = 5;
  12.  
  13.         private T[] entities;
  14.  
  15.         private int counter;
  16.  
  17.  
  18.         public T this[int i]
  19.         {
  20.             get
  21.             {
  22.                 // This indexer is very simple, and just returns or sets
  23.                 // the corresponding element from the internal array.
  24.                 return entities[i];
  25.             }
  26.             set
  27.             {
  28.                 entities[i] = value;
  29.             }
  30.         }
  31.  
  32.         public Queue()
  33.             : this(CAPACITY)
  34.         { }
  35.  
  36.         public Queue(int capacity)
  37.         {
  38.             entities = new T[capacity];
  39.         }
  40.  
  41.         public void Enqueue(T entity)
  42.         {
  43.             if (counter >= entities.Length) {
  44.                 throw new InvalidOperationException("The queue is full");
  45.             }
  46.             entities[counter] = entity;
  47.             counter++;
  48.  
  49.         }
  50.  
  51.         public T Dequeue()
  52.         {
  53.             if (counter == 0) {
  54.                 throw new InvalidOperationException("The queue is empty");
  55.             }
  56.             T temp = entities[0];
  57.             for (int i = 0; i < entities.Length - 1; i++)
  58.             {
  59.                 entities[i] = entities[i + 1];    
  60.             }
  61.             entities[counter - 1] = default(T);
  62.             counter--;
  63.             return temp;
  64.         }
  65.  
  66.         public int GetNumberOfEntities()
  67.         {
  68.             return counter;
  69.         }
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment