Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using Wintellect.PowerCollections;
- public class FirstLastList<T> : IFirstLastList<T>
- where T : IComparable<T>
- {
- private readonly LinkedList<T> elements = new LinkedList<T>();
- private readonly SortedDictionary<T, List<LinkedListNode<T>>> nodes = new SortedDictionary<T, List<LinkedListNode<T>>>();
- private readonly OrderedBag<T> orderedElements = new OrderedBag<T>();
- private readonly OrderedBag<T> reversedOrderedElements = new OrderedBag<T>((e1, e2) => e2.CompareTo(e1));
- public void Add(T newElement)
- {
- var node = this.elements.AddLast(newElement);
- if (!this.nodes.ContainsKey(newElement))
- {
- this.nodes.Add(newElement, new List<LinkedListNode<T>>());
- }
- this.nodes[newElement].Add(node);
- this.orderedElements.Add(newElement);
- this.reversedOrderedElements.Add(newElement);
- }
- public int Count => this.orderedElements.Count;
- public IEnumerable<T> First(int count)
- {
- if (count > this.orderedElements.Count)
- {
- throw new ArgumentOutOfRangeException(nameof(count));
- }
- return this.elements.Take(count);
- }
- public IEnumerable<T> Last(int count)
- {
- if (count > this.orderedElements.Count)
- {
- throw new ArgumentOutOfRangeException(nameof(count));
- }
- var result = new T[count];
- var current = this.elements.Last;
- for (int i = 0; i < count; i++)
- {
- result[i] = current.Value;
- current = current.Previous;
- }
- return result;
- }
- public IEnumerable<T> Min(int count)
- {
- if (count > this.orderedElements.Count)
- {
- throw new ArgumentOutOfRangeException(nameof(count));
- }
- return this.orderedElements.Take(count);
- }
- public IEnumerable<T> Max(int count)
- {
- if (count > this.orderedElements.Count)
- {
- throw new ArgumentOutOfRangeException(nameof(count));
- }
- return this.reversedOrderedElements.Take(count);
- }
- public int RemoveAll(T element)
- {
- var count = this.orderedElements.RemoveAllCopies(element);
- this.reversedOrderedElements.RemoveAllCopies(element);
- if (count > 0)
- {
- var nodesToRemove = this.nodes[element];
- foreach (var linkedListNode in nodesToRemove)
- {
- this.elements.Remove(linkedListNode);
- }
- this.nodes.Remove(element);
- }
- return count;
- }
- public void Clear()
- {
- this.elements.Clear();
- this.nodes.Clear();
- this.orderedElements.Clear();
- this.reversedOrderedElements.Clear();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement