Реализовать List так, что при добавлении элемента в конец, удаляется тот, что в начале - C#
Формулировка задачи:
Добрый день. Не как не могу найти готовый способ цикличного листа, пример: у нас есть лист размером в 10 ячеек, когда заполняется последняя ячейка, самый первый элемент удаляется. Вообще в c# есть готовые реализации или нет?
Решение задачи: «Реализовать List так, что при добавлении элемента в конец, удаляется тот, что в начале»
textual
Листинг программы
- using System;
- using System.Collections;
- using System.Collections.Generic;
- namespace ConsoleApplication36
- {
- class Program
- {
- static void Main(string[] args)
- {
- var queue = new LimitedQueue<int>(30);
- for (int i = 0; i < 20; i++)
- {
- queue.Enqueue(i);
- }
- foreach (int x in queue)
- {
- Console.WriteLine(x);
- }
- }
- }
- public class LimitedQueue<T> : IEnumerable<T>
- {
- private readonly T[] _items;
- private int _currentPos;
- private int _currentStart;
- public LimitedQueue(int capacity)
- {
- _items = new T[capacity];
- }
- public void Enqueue(T item)
- {
- if (_currentPos == _currentStart)
- {
- IncrementNoOverflow(ref _currentStart);
- }
- _items[_currentPos] = item;
- if (Count < Capacity)
- {
- Count++;
- }
- IncrementNoOverflow(ref _currentPos);
- }
- public T Dequeue()
- {
- T result = _items[_currentPos];
- Count--;
- DecrementNoOverflow(ref _currentPos);
- return result;
- }
- public int Count { get; private set; }
- public int Capacity
- {
- get { return _items.Length; }
- }
- public IEnumerator<T> GetEnumerator()
- {
- for (int i = _currentStart; i < Count; i++)
- {
- yield return _items[i];
- }
- for (int i = 0; i < _currentStart && i < Count; i++)
- {
- yield return _items[i];
- }
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- private void IncrementNoOverflow(ref int value)
- {
- value++;
- if (value == Capacity)
- value = 0;
- }
- private void DecrementNoOverflow(ref int value)
- {
- value--;
- if (value < 0)
- value = Capacity - 1;
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д