Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- public class ReversedList<T> : IEnumerable<T>
- {
- private T[] elements;
- public int Count { get; private set; }
- public int Capacity { get; private set; }
- public ReversedList()
- {
- this.Capacity = 2;
- this.elements = new T[this.Capacity];
- }
- public T this[int index]
- {
- get
- {
- CheckArrLenght(index);
- return this.elements[index];
- }
- set
- {
- CheckArrLenght(index);
- this.elements[index] = value;
- }
- }
- public void Add(T item)
- {
- if (this.Count == 0)
- {
- this.elements[this.Count] = item;
- this.Count++;
- return;
- }
- if (this.Count >= this.elements.Length)
- {
- this.Grow();
- }
- var newElements = new T[this.Capacity];
- this.CopyAllElementsTo(newElements, item);
- this.elements = newElements;
- }
- public T RemoveAt(int index)
- {
- CheckArrLenght(index);
- T deletedElement = this.elements[index];
- for (int i = index; i < this.Count; i++)
- {
- this.elements[i] = this.elements[i + 1];
- }
- this.Count--;
- if (this.Count <= this.elements.Length / 4)
- {
- this.Shrink();
- }
- return deletedElement;
- }
- public IEnumerator<T> GetEnumerator()
- {
- var currentElement = 0;
- while (currentElement < this.elements.Length -1)
- {
- yield return this.elements[currentElement];
- currentElement++;
- }
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return this.GetEnumerator();
- }
- private void Shrink()
- {
- T[] newArr = new T[this.elements.Length / 2];
- Array.Copy(this.elements, newArr, this.Count);
- this.elements = newArr;
- }
- private void CopyAllElementsTo(T[] newElements, T item)
- {
- newElements[0] = item;
- Count++;
- for (int i = 1; i < this.Count; i++)
- {
- newElements[i] = this.elements[i - 1];
- }
- }
- private void CheckArrLenght(int index)
- {
- if (index < 0 || index >= this.Count)
- {
- throw new ArgumentOutOfRangeException();
- }
- }
- private void Grow()
- {
- this.Capacity *= 2;
- var newElements = new T[this.Capacity];
- Array.Copy(this.elements, newElements, this.Count);
- this.elements = newElements;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment