我目前正在使用C#中的通用链表,我需要对列表中的节点进行排序。
namespace ConsoleApplication1
{
// T is the type of data stored in a particular instance of GenericList.
public class GenericList<T>
{
private class Node
{
// Each node has a reference to the next node in the list.
public Node Next;
// Each node holds a value of type T.
public T Data;
}
// The list is initially empty.
private Node head = null;
// Add a node at the beginning of the list with t as its data value.
public void AddNode(T t)
{
Node newNode = new Node();
newNode.Next = head;
newNode.Data = t;
head = newNode;
}
// The following method returns the data value stored in the last node in
// the list. If the list is empty, the default value for type T is
// returned.
public T GetFirstAdded()
{
// The value of temp is returned as the value of the method.
// The following declaration initializes temp to the appropriate
// default value for type T. The default value is returned if the
// list is empty.
T temp = default(T);
Node current = head;
while (current != null)
{
temp = current.Data;
current = current.Next;
}
return temp;
}
}
}
有什么想法吗?
答案 0 :(得分:1)
我会以这种方式略微更改列表:
// implement IEnumerable<T>
public class GenericList<T> : IEnumerable<T>
{
#region Constructors
public GenericList()
{
}
public GenericList(IEnumerable<T> values)
: this()
{
foreach (var val in values)
this.AddNode(val);
}
#endregion
#region IEnumerable Implementations
public IEnumerator<T> GetEnumerator()
{
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region Nested Enumerator
class Enumerator : IEnumerator<T>
{
private GenericList<T> innerList;
private Node current;
private bool started;
public Enumerator(GenericList<T> list)
{
this.innerList = list;
this.current = null;
started = false;
}
public T Current
{
get
{
if (!started)
throw new InvalidOperationException("You can't ask Current before calling MoveNext()");
return current.Data;
}
}
object System.Collections.IEnumerator.Current
{
get { return this.Current; }
}
public bool MoveNext()
{
if (!started)
{
current = innerList.head;
started = true;
}
else
{
current = current.Next;
}
if (current != null)
return true;
return false;
}
public void Reset()
{
started = false;
current = null;
}
public void Dispose()
{
}
}
#endregion
#region Your methods i.e. AddNode() etc.
//...
#endregion
}
实现IEnumerable<T>
您可以在列表中使用LINQ OrderBy()
和OrderByDescending()
方法(以及使用foreach
进行迭代),新构造函数允许您创建一个新的链表更容易:
var sortedList = new GenericList<int>(unsortedList.OrderBy(x => x));
答案 1 :(得分:0)
我觉得你想问:
“我对列表中的对象类别一无所知!我怎么能对我一无所知的对象列表进行排序?!”
以下是该问题的答案。
您的T类型应该实现interface。 IComparable可能就是你想要的那个。这将为您提供一种方法,通过要求它们具有比较方法来比较传入的对象。类似的东西:
public class GenericList<T> where T : System.IComparable<T>
这样做确保无论你为这个List做什么泛型类,该类都将有一个CompareTo方法,允许该类的对象与该类的其他对象进行比较。比较是分类的基本必要条件。
连接完成后,您可以使用自己喜欢的排序算法对列表进行排序,并使用CompareTo(T项)方法。简单的算法包括insertion sort和selection sort。雄心勃勃的人可以尝试merge sort。
如果这不是您的意思,请告诉我们,我们可以了解您遇到的问题。