我創建了一個自定義鏈接串列,代碼如下。現在嘗試實作一種排序(這是我告訴要做的,而不是我所知道的最佳選擇),我們如何以最佳時間復雜度或最佳方法進行
我的自定義鏈表我的疑問是在最后一個節點上,在冒泡排序的每個階段應該嘗試最后排序然后從第一個節點開始,如何處理最后一個節點作為它指向第一個節點
public class CustomCircularList<T> : ICollection<T>, IEnumerable<T>
{
Node<T> head = null;
Node<T> tail = null;
int count = 0;
readonly IEqualityComparer<T> comparer;
public int Count { get { return count; } }
public bool IsReadOnly { get { return false; } }
public void Add(T item)
{
this.AddLast(item);
}
AddLast...
}
}
我的 Node 類具有三個屬性
public T Value { get; private set; }
public Node<T> Next { get; set; }
public Node<T> Previous { get; set; }
我像這樣將 IComparer 添加到我的班級 T 中,并嘗試像下面那樣作業
public class Fund: IComparer<Fund>
{
public string fundname{ get; set; }
public int Compare([AllowNull] Fund x, [AllowNull] Fund y)
{
if (x == null || y == null)
{
return 0;
}
return x.fundname.CompareTo(y.fundname);
}
uj5u.com熱心網友回復:
首先,讓我假設Node<T>物件具有(至少)2 個標準屬性:Value和Next:
public class Node<T> {
...
public T Value {get; set;}
public Node<T> Next {get;}
}
既然你有回圈鏈表,
tail.Next == head
我們可以列舉所有的專案除了最后一個為
for (Node<T> node = head; !ReferenceEquals(node.Next, head); node = node.Next) {
...
}
僅供參考,如果我們有一個鏈表(非回圈),回圈將是(我們應該做的就是head改為null):
for (Node<T> node = head; !ReferenceEquals(node.Next, null); node = node.Next) {
...
}
代碼可以是
public void BubbleSort(IComparer<T> comparer = null) {
comparer ??= Comparer<T>.Default;
if (comparer is null)
throw new ArgumentNullException(nameof(comparer));
if (head is null)
return; // empty linked list
bool agenda = true;
while (agenda) {
agenda = false;
for (Node<T> node = head; !ReferenceEquals(node.Next, head); node = node.Next)
if (comparer.Compare(node.Value, node.Next.Value) > 0) {
agenda = true;
var help = node.Value;
node.Value = node.Next.Value;
node.Next.Value = help;
}
}
}
編輯:如果你想對一些自定義型別(T)進行排序,你應該確保T實作IComparable<T>:
public class MyClass: IComparable<MyClass> {
...
public int CompareTo(MyClass other) {
TODO: return 0 if other == this, -1 if this < other, 1 if this > other
}
}
或者您應該實作一個比較器 IComparer<MyClass>,您應該將其作為引數提供:
public class MyComparer<MyClass> {
public int Compare(MyClass x, MyClass y) {
//TODO: return 0 when x == y, -1 when x < y, when x > y
}
}
然后
MyCircularLinkedList.BubbleSort(new MyComparer());
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/373434.html
上一篇:使用facet_grid在ggplot中對facet進行排序
下一篇:我對刺痛數字進行排序有錯誤的結果
