Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace MyCollections
- {
- public class MyQueue<T> : IEnumerable<T>
- {
- private const int _startCapacity = 8;
- private T[] _items;
- private int _capacity;
- private int _head;
- private int _tail;
- public int Count { get; private set; }
- public MyQueue()
- {
- _items = new T[_startCapacity];
- _capacity = _startCapacity;
- }
- public void Enqueue(T item)
- {
- if (Count == _capacity)
- ExtendInnerArray();
- _items[_head] = item;
- _head++;
- Count++;
- if (_head == _capacity)
- _head = 0;
- }
- private void ExtendInnerArray()
- {
- if (_capacity == Array.MaxLength)
- throw new OutOfMemoryException();
- int newCapacity = 2 * _capacity;
- if ((uint)newCapacity > Array.MaxLength)
- newCapacity = Array.MaxLength;
- T[] newItems = new T[newCapacity];
- if (_tail < _head)
- {
- Array.Copy(_items, _head, newItems, 0, Count);
- }
- else
- {
- Array.Copy(_items, _tail, newItems, 0, _capacity - _tail);
- Array.Copy(_items, 0, newItems, _capacity - _tail, _head);
- }
- _items = newItems;
- _tail = 0;
- _head = _capacity;
- _capacity = newCapacity;
- }
- public T Dequeue()
- {
- if (Count == 0)
- throw new InvalidOperationException("Queue is empty");
- T returnValue = _items[_tail];
- Count--;
- _tail++;
- if (_tail == _capacity)
- _tail = 0;
- return returnValue;
- }
- public T Peek()
- {
- if (Count == 0)
- throw new InvalidOperationException("Queue is empty");
- return _items[_tail];
- }
- public IEnumerator<T> GetEnumerator()
- {
- int index = _tail;
- for (int i = 0; i < Count; i++)
- {
- yield return _items[index];
- index++;
- if (index == _capacity)
- index = 0;
- }
- yield break;
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement