StreetKatya

MyQueue

Feb 13th, 2023
1,072
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.91 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 CustomQueue
  8. {
  9.     public class MyQueue <T>
  10.     {
  11.         private T[] _items;
  12.         private int head, tail;
  13.         public int Count { get; private set; }
  14.         private int _capacity;
  15.  
  16.         public MyQueue()
  17.         {
  18.             _capacity = 4;
  19.             _items = new T[_capacity];
  20.             head = 0; tail = 0;
  21.             Count = 0;
  22.         }
  23.         #region Methods
  24.         /// In Process:
  25.         /// Ready: Push(), Pop(), Peek(), Count, Contains();
  26.         public void Push(T item)
  27.         {
  28.             if(Count == _capacity)
  29.             {
  30.                 ExpandedCapacityQueue();
  31.             }
  32.             _items[tail % _capacity] = item;
  33.             tail++; Count++;
  34.         }
  35.         public T Pop()
  36.         {
  37.             if(Count == 0)
  38.             {
  39.                 throw new ArgumentException("NoSuchElementException");
  40.             }
  41.             else
  42.             {
  43.                 T item = _items[head % _capacity];
  44.                 head++; Count--;
  45.                 return item;
  46.             }
  47.         }
  48.         public T Peek()
  49.         {
  50.             if (Count == 0)
  51.             {
  52.                 throw new ArgumentException("NoSuchElementException");
  53.             }
  54.             else
  55.             {
  56.                 return _items[head % _capacity];
  57.             }
  58.         }
  59.         public bool Contains(T item)
  60.         {
  61.             return _items.Contains(item);
  62.         }
  63.         private void ExpandedCapacityQueue()
  64.         {
  65.             T[] tempitems = _items;
  66.             _items = new T[_capacity * 2];
  67.             for (int i = 0; i < Count; i++)
  68.             {
  69.                 _items[i] = tempitems[(head + i) % _capacity];
  70.             }
  71.             head = 0;
  72.             _capacity = _capacity * 2;
  73.         }
  74.         #endregion
  75.     }
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment