简体   繁体   English

排序通用链表

[英]Sorting generic linked list

I have everything in a Generic Linked list done except for sorting. 除了排序之外,我已经完成了通用链接列表中的所有操作。 And I don't know how to use IComparable or how I would go about doing this because it's generic. 而且我不知道如何使用IComparable或者我将如何使用它,因为它是通用的。 I don't know what I would even be comparing or sorting? 我不知道我甚至会比较或排序?

public class Node<T> : IComparable<T>
{
    private Node<T> next;
    private T item;

}

So 所以

public int CompareTo( T other )
{
    // TODO: Find out how to do it properly
    throw new NotImplementedException();
}

It is also against the instructions to convert it to an array and then sort it, then convert it back. 它也反对将它转换为数组然后对其进行排序然后将其转换回来的指令。

Having a linked list Node object implement IComparable makes absolutely no sense for the exact reasons you describe. 拥有链接列表Node对象实现IComparable对于您描述的确切原因完全没有意义。 Instead, the classes that you use in the linked list should implement it. 相反,您在链表中使用的类应该实现它。 In fact, you can require this with a generic type constraint: 实际上,您可以使用泛型类型约束来要求:

MyClass<T> where T : IComparable<T> {}

With that done, you can use T as if it were an IComparable when performing your sort. 完成后,您可以在执行排序时使用T ,就好像它 IComparable一样。

The first thing you ought to do is to read up on sort algorithms and decide which one you're going to use. 你应该做的第一件事是阅读排序算法并决定你将使用哪一个。 Once you've done that, you can worry about comparing your generic values. 完成后,您可以担心比较通用值。

If you want to follow the framework approach, don't require your T to implement IComparable<T>. 如果您想遵循框架方法,请不要让您的T实现IComparable<T>. Instead, use Comparer<T>.Default . 而是使用Comparer<T>.Default This approach allows you to write your class to support user-defined comparisons: 这种方法允许您编写类以支持用户定义的比较:

public class LinkedList<T>
{
    public void Sort() { this.Sort(Comparer<T>.Default); }
    public void Sort(IComparer<T> comparer)
    {
        //todo: implement
        throw new NotImplementedException();
    }
}

My initial version of this answer had the comparer as a property of the class, but that's really incorrect, because a linked list is not an inherently sorted type. 我的这个答案的初始版本将比较器作为类的属性,但这确实是不正确的,因为链表不是固有的排序类型。 You might want to sort the list one way once, and then 2 seconds later sort it a different way. 您可能希望以一种方式对列表进行排序,然后在2秒后以不同的方式对其进行排序。 The comparer should therefore be a parameter of the sort method. 因此,比较器应该是sort方法的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM