不知道是不是我引起的话题,老赵出了个O1的面试题。
public class MyClass<T> : IMyList<T>
{
bool isReversed = false;
LinkedList<T> list = new LinkedList<T>();
Dictionary<T, List<T>> dic = new Dictionary<T, List<T>>();
public void AddFirst(T item)
{
if (!isReversed)
{
list.AddFirst(item);
}
else
{
list.AddLast(item);
}
CacheItemInDic(item);
}
private void CacheItemInDic(T item)
{
List<T> sameValueItems;
if (!dic.TryGetValue(item,out sameValueItems))
{
sameValueItems = new List<T>();
}
sameValueItems.Add(item);
}
public void AddLast(T item)
{
if (!isReversed)
{
list.AddLast(item);
}
else
{
list.AddFirst(item);
}
CacheItemInDic(item);
}
public void Remove(T item)
{
T cachedItem;
List<T> sameValueItems;
if (!dic.TryGetValue(item, out sameValueItems))
{
return;
}
else
{
cachedItem = sameValueItems[0];
list.Remove(item);
}
public void Reverse()
{
isReversed = !isReversed; ;
}
public IEnumerator<T> GetEnumerator()
{
throw new NotImplementedException();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public class MyClass<T> : IMyList<T>
{
bool isReversed = false;
LinkedList<T> list = new LinkedList<T>();
Dictionary<T, List<LinkedListNode<T>>> dic = new Dictionary<T, List<LinkedListNode<T>>>();
public void AddFirst(T item)
{
LinkedListNode<T> node;
if (!isReversed)
{
node = list.AddFirst(item);
}
else
{
node = list.AddLast(item);
}
CacheItemInDic(item,node);
}
private void CacheItemInDic(T item,LinkedListNode<T> node)
{
List<LinkedListNode<T>> sameValueNodes;
if (!dic.TryGetValue(item,out sameValueNodes))
{
sameValueNodes = new List<LinkedListNode<T>>();
}
sameValueNodes.Add(node);
}
public void AddLast(T item)
{
LinkedListNode<T> node;
if (!isReversed)
{
node = list.AddLast(item);
}
else
{
node = list.AddFirst(item);
}
CacheItemInDic(item, node);
}
public void Remove(T item)
{
LinkedListNode<T> cachedNode;
List<LinkedListNode<T> > sameValueNodes;
if (!dic.TryGetValue(item, out sameValueNodes))
{
return;
}
else
{
cachedNode = sameValueNodes[0];
}
if (cachedNode == null) return;
list.Remove(cachedNode);
}
public void Reverse()
{
isReversed = !isReversed; ;
}
public IEnumerator<T> GetEnumerator()
{
LinkedListNode<T> node;
if (!isReversed)
node = list.First;
else
node = list.Last;
while (true)
{
if (node == null)
yield break;
yield return node.Value;
if (!isReversed)
node = node.Next;
else
node = node.Previous;
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
static void Main()
{
MyClass<int> collection = new MyClass<int>();
for (int i = 1; i < 11; i++)
{
if(i%2 ==0)
collection.AddFirst(i);
else
collection.AddLast(i);
}
foreach (var i in collection)
{
Console.WriteLine(i);
}
collection.Reverse();
foreach (var i in collection)
{
Console.WriteLine(i);
}
}