Реализовать List так, что при добавлении элемента в конец, удаляется тот, что в начале - C#

Узнай цену своей работы

Формулировка задачи:

Добрый день. Не как не могу найти готовый способ цикличного листа, пример: у нас есть лист размером в 10 ячеек, когда заполняется последняя ячейка, самый первый элемент удаляется. Вообще в c# есть готовые реализации или нет?

Решение задачи: «Реализовать List так, что при добавлении элемента в конец, удаляется тот, что в начале»

textual
Листинг программы
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4.  
  5. namespace ConsoleApplication36
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             var queue = new LimitedQueue<int>(30);
  12.             for (int i = 0; i < 20; i++)
  13.             {
  14.                 queue.Enqueue(i);
  15.             }
  16.             foreach (int x in queue)
  17.             {
  18.                 Console.WriteLine(x);
  19.             }
  20.  
  21.         }
  22.     }
  23.  
  24.     public class LimitedQueue<T> : IEnumerable<T>
  25.     {
  26.         private readonly T[] _items;
  27.         private int _currentPos;
  28.         private int _currentStart;
  29.  
  30.         public LimitedQueue(int capacity)
  31.         {
  32.             _items = new T[capacity];
  33.         }
  34.  
  35.         public void Enqueue(T item)
  36.         {
  37.             if (_currentPos == _currentStart)
  38.             {
  39.                 IncrementNoOverflow(ref _currentStart);
  40.             }
  41.             _items[_currentPos] = item;
  42.             if (Count < Capacity)
  43.             {
  44.                 Count++;
  45.             }
  46.             IncrementNoOverflow(ref _currentPos);
  47.         }
  48.  
  49.         public T Dequeue()
  50.         {
  51.             T result = _items[_currentPos];
  52.             Count--;
  53.             DecrementNoOverflow(ref _currentPos);
  54.             return result;
  55.         }
  56.  
  57.         public int Count { get; private set; }
  58.        
  59.         public int Capacity
  60.         {
  61.             get { return _items.Length; }
  62.         }
  63.  
  64.         public IEnumerator<T> GetEnumerator()
  65.         {
  66.             for (int i = _currentStart; i < Count; i++)
  67.             {
  68.                 yield return _items[i];
  69.             }
  70.             for (int i = 0; i < _currentStart && i < Count; i++)
  71.             {
  72.                 yield return _items[i];
  73.             }
  74.         }
  75.  
  76.         IEnumerator IEnumerable.GetEnumerator()
  77.         {
  78.             return GetEnumerator();
  79.         }
  80.  
  81.         private void IncrementNoOverflow(ref int value)
  82.         {
  83.             value++;
  84.             if (value == Capacity)
  85.                 value = 0;
  86.         }
  87.  
  88.         private void DecrementNoOverflow(ref int value)
  89.         {
  90.             value--;
  91.             if (value < 0)
  92.                 value = Capacity - 1;
  93.         }
  94.     }
  95. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

7   голосов , оценка 4.143 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы