Предмет: Информатика, автор: dmasya

составить программу на C#
Написать класс Queue, соответствующий очереди. В классе должны быть реализованы
следующие методы: Enqueue – добавление элемента в очередь, Dequeue – извлечение элемента из
очереди с возвратом удаленного значения, Peek – возврат элемента из начала очереди без его
удаления, IsEmpty – проверка пустоты очереди, Clear – очистка очереди. Также необходимо
переопределить унаследованный метод ToString для получения представления очереди в виде
строки.

Ответы

Автор ответа: iknowthatyoufeelbro
2

Ответ:

using System;

using System.Collections.Generic;

using System.Text;

namespace MyQueue

{

   public class QueueException : Exception { }

   public class Queue <T>

   {

       private const int _basicCapacity = 8;

       private int _capacity;

       private int _count;

       private T[] _items;

       private int _begin;

       private int _end;

       

       public int Capacity

       {

           get => _capacity;

           protected set

           {

               int newCapacity = value;

               T[] newItems = new T[newCapacity];

               Count = Math.Min(Count, Capacity);

               for (int i = 0; i < Count; i++)

               {  

                   newItems[i] = _items[(_begin + i) % Capacity];

               }

               _begin = 0;

               _end = Count;

               _items = newItems;

               _capacity = newCapacity;

           }

       }

       

       public int Count

       {

           get => _count;

           protected set => _count = value;

       }

       

       public Queue()

       {

           Capacity = _basicCapacity;

           Count = 0;

           _begin = 0;

           _end = 0;

           _items = new T[Capacity];

       }

       

       public void Enqueue(T item)

       {

           if (Count == Capacity)

           {

               Capacity *= 2;

           }

           Count++;

           _items[_end] = item;

           _end = (_end+1) % Capacity;

       }

       

       public bool IsEmpty()

       {

           return Count == 0;

       }

       

       public T Dequeue()

       {

           if (IsEmpty())

           {

               throw new QueueException();

           }

           T item = _items[_begin];

           _begin = (_begin+1) % Capacity;

           Count--;

           if (Count * 4 < Capacity)

           {

               int newCapacity = Math.Max(Capacity / 4, _basicCapacity);

               if (newCapacity < Capacity)

               {

                   Capacity = newCapacity;

               }

           }

           return item;

       }

       

       public T Peek()

       {

           if (IsEmpty())

           {

               throw new QueueException();

           }

           return _items[_begin];

       }

       

       public override string ToString()

       {

           StringBuilder sb = new StringBuilder();

           for(int i = 0; i < Count; i++){

               if (i > 0)

               {

                   sb.Append(" ");

               }

               sb.Append(_items[(_begin+i) % Capacity].ToString());

           }

           return sb.ToString();

       }

       

       public void Clear()

       {

           Count = 0;

           _begin = 0;

           _end = 0;

           if (Capacity > _basicCapacity)

           {

               Capacity = _basicCapacity;

           }

       }

   }

   

   class Program

   {

       public static void Main (string[] args)

       {

           Queue <double> q = new Queue <double>();

           for(int i = 0; i < 20; i++){

               q.Enqueue(i);

           }

           Console.WriteLine("0-19: \"{0}\"", q.ToString());

           for(int i = 0; i < 10; i++)

           {

               Console.WriteLine("Peek: {0}", q.Peek());

               Console.WriteLine("Dequeue: {0}", q.Dequeue());

           }

           Console.WriteLine("10-19: \"{0}\"", q.ToString());

           q.Clear();

           Console.WriteLine("Empty queue representation: \"{0}\"", q.ToString());

           Console.WriteLine("Queue is empty? {0}", q.IsEmpty());

       }

   }

}

Объяснение:

Реализация циклической очереди с примерами использования.

Тот же самый код тут: onlinegdb.com/SkyJfEvnS


dmasya: спасибо большое
iknowthatyoufeelbro: Можно еще попробовать сделать на основе односвязного списка, там вроде предыдущее задание было про список
Похожие вопросы
Предмет: Химия, автор: Kkkasaassatyygyc
Предмет: Биология, автор: Аноним