HashLinkedList.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. using System.Collections.Generic;
  2. using MongoDB.Bson.IO;
  3. namespace ET
  4. {
  5. public class HashLinkedList<T, K>
  6. {
  7. private Dictionary<T, LinkedListNode<K>> dict = new Dictionary<T, LinkedListNode<K>>();
  8. private LinkedList<K> linkedList = new LinkedList<K>();
  9. public K this[T t]
  10. {
  11. get
  12. {
  13. if (this.dict.ContainsKey(t))
  14. {
  15. return this.dict[t].Value;
  16. }
  17. return default;
  18. }
  19. }
  20. public int Count
  21. {
  22. get
  23. {
  24. return this.dict.Count;
  25. }
  26. }
  27. public K First
  28. {
  29. get
  30. {
  31. var first = this.linkedList.First;
  32. if (first == null)
  33. {
  34. return default;
  35. }
  36. return first.Value;
  37. }
  38. }
  39. public K Last
  40. {
  41. get
  42. {
  43. var last = this.linkedList.Last;
  44. if (last == null)
  45. {
  46. return default;
  47. }
  48. return last.Value;
  49. }
  50. }
  51. public bool AddLast(T t, K k)
  52. {
  53. if (this.dict.ContainsKey(t))
  54. {
  55. return false;
  56. }
  57. LinkedListNode<K> node = this.linkedList.AddLast(k);
  58. this.dict.Add(t, node);
  59. return true;
  60. }
  61. public bool AddFirst(T t, K k)
  62. {
  63. if (this.dict.ContainsKey(t))
  64. {
  65. return false;
  66. }
  67. LinkedListNode<K> node = this.linkedList.AddFirst(k);
  68. this.dict.Add(t, node);
  69. return true;
  70. }
  71. public K Remove(T t)
  72. {
  73. LinkedListNode<K> node;
  74. if (this.dict.TryGetValue(t, out node))
  75. {
  76. K value = node.Value;
  77. this.dict.Remove(t);
  78. this.linkedList.Remove(node);
  79. return value;
  80. }
  81. return default;
  82. }
  83. public bool ContainsKey(T t)
  84. {
  85. return this.dict.ContainsKey(t);
  86. }
  87. public LinkedList<K>.Enumerator GetEnumerator()
  88. {
  89. return this.linkedList.GetEnumerator();
  90. }
  91. public void Clear()
  92. {
  93. this.dict.Clear();
  94. this.linkedList.Clear();
  95. }
  96. }
  97. }