我已经从头开始在C#中建立了一个链表,并且具有可靠的单元测试覆盖率,以确保它有效。
为了轻松地比较链接列表和许多值,我使用标准手动“枚举”值,而CurrentNode.Next!= null,提前技术并将这些值存储在C#列表或数组中。
我想在我的自定义LinkedList类上实现IEnumerable,而不是依赖于从私有后备集合中获取枚举器。
这是我的LinkedList类的代码。我觉得我忽略了一些简单的东西,因为枚举器应该只是你从集合类中获得的对象,它提供了一个起点和下一个方法,据我所知。我只是不能让它以通用的方式工作。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpLibrary.DataStructures.LinkedLists
{
public class LinkedList<T> : IEnumerable<T>
{
public Node<T> First { get; private set; }
public Node<T> Current { get; set; }
public LinkedList(T initialValue)
{
First = new Node<T>(initialValue);
}
public void AddNodeToEnd(T value)
{
Node<T> last = GetLastNode();
last.Next = new Node<T>(value);
}
public Node<T> GetLastNode()
{
Node<T> last = First;
Node<T> current = First;
while (current.Next != null)
{
last = current.Next;
current = current.Next;
}
return current;
}
public void Reset()
{
Current = First;
}
public IEnumerator<T> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
}
答案 0 :(得分:4)
要添加到Bradley的答案,请注意返回IEnumerator<T>
的方法也支持yield
关键字:
public class LinkedList<T> : IEnumerable<T>
{
...
// this will automagically create the
// appropriate class for you
public IEnumerator<T> GetEnumerator()
{
Node<T> current = First;
while (current != null)
{
yield return current.Value;
current = current.Next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
// this will invoke the public generic
// version, so there is no recursion
return this.GetEnumerator();
}
}
但是,您应该从父类中删除Current
和Reset()
,它们不属于那里。并且您的GetLastNode()
方法有两个重复的变量,您可以删除其中一个。
答案 1 :(得分:3)
由于您已创建自定义集合,因此无法仅使用现有的IEnumerator
实现。你需要创建一个:
public class LinkedListEnumerator<T> : IEnumerator<T>
{
public LinkedListEnumerator(LinkedList<T> collection)
{
}
...
}
我将要枚举的集合传递给构造函数。其他方式可行,但这似乎是最简单的方法。现在您的IEnumerable<T>
实施是:
public IEnumerator<T> GetEnumerator()
{
return new LinkedListEnumerator<T>(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new LinkedListEnumerator<T>(this);
}
实际IEnumerator
实施作为练习。
答案 2 :(得分:0)
仅供参考,这是一个懒惰版本,您无需自己创建Enumerator,而可以使用List的和递归功能:
T [] nextNodes;
public IEnumerator GetEnumerator ()
{
var list = new List<T> ();
ForEach ( n => list.Add ( n ) );
return list.GetEnumerator ();
}
public void ForEach ( Action<T> action )
{
action ( this );
foreach (var node in nextNodes)
node.ForEach ( action );
}
如果您知道您的链表中没有很多元素并且不需要最大性能,这就足够了,因为复杂度变为:2 * O(n)。