C#实现单链表排序

合集下载
相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

首先写一个单链表的C#实现:

public class Link

{

public Link Next;

public string Data;

public Link(Link next, string data)

{

this.Next = next;

this.Data = data;

}

}

无外乎是冒泡、选择、插入等排序方法。关键是交换算法,需要额外考虑,此处选择了插入排序算法,如下所示:

public static Link SortLink(Link head)

{

Link pre1 = head;

Link pre2 = head.Next;

Link min = null;

for (Link curr1 = head.Next; curr1 != null; curr1 = min.Next)

{

if (curr1.Next == null)

break;

min = curr1;

for (Link curr2 = curr1.Next; curr2 != null; curr2 = curr2.Next)

{

//swap curr1 and curr2

if (curr2.Data < curr1.Data)

{

min = curr2;

curr2 = curr1;

curr1 = min;

pre1.Next = curr1;

curr2.Next = curr1.Next;

curr1.Next = pre2;

//if exchange element n-1 and n, no need to add reference from pre2 to curr2, because they are the same one

if (pre2 != curr2)

pre2.Next = curr2;

}

pre2 = curr2;

}

pre1 = min;

pre2 = min.Next;

}

return head;

}

相关文档
最新文档