【发布时间】:2009-07-25 21:19:23
【问题描述】:
我在为单个列表实现排序算法(合并)时遇到问题,定义如下 我的mergesort方法总是给我null..我无法弄清楚出了什么问题 你们能帮帮我吗?
节点类
public class Node
{
private int data;
private Node next;
}
链表类
public class SSL
{
private Node head;
}
我的合并排序代码
public static void MergeSort(SSL a)
{
SSL x = new SSL();
SSL y = new SSL();
if (a.Head == null || a.Head.Next == null) // base case if list has 0 or 1 element
return;
AlternateSplitting(a, x, y);
MergeSort(x);
MergeSort(y);
a = SortedMerge(x, y);
}
我实现了以下辅助方法来实现归并排序
AlternateSplitting:此方法会将列表拆分为 2 个列表
public static void AlternateSplitting(SSL src, SSL odd, SSL even)
{
while (src.Head != null)
{
MoveNode(odd, src);
if (src.Head != null)
MoveNode(even, src);
}
} // end of AlternateSplitting
此方法将合并2个列表并返回一个新列表
public static SSL SortedMerge(SSL a, SSL b)
{
SSL c = new SSL();
if (a.Head == null)
return b;
else
if (b.Head == null)
return a;
else
{
bool flagA = false;
bool flagB = false;
Node currentA = new Node();
Node currentB = new Node();
while (!flagA && !flagB)
{
currentA = a.Head;
currentB = b.Head;
if (currentA.Data < currentB.Data)
{
MoveNodeToEnd(a, c);
currentA = a.Head;
if (currentA== null)
flagA = true;
}
else
if (currentA.Data > currentB.Data)
{
MoveNodeToEnd(b, c);
currentB = b.Head;
if (currentB== null)
flagB = true;
}
} // end of while
if (flagA)
{
while (currentB != null)
{
MoveNodeToEnd(b, c);
currentB = b.Head;
}
}
else
if(flagB)
{
while (currentA != null)
{
MoveNodeToEnd(a, c);
currentA = a.Head;
}
}
return c;
} // end of outer else
} // end of function sorted merge
【问题讨论】:
-
可能。 MoveNode 和 MoveNodeToEnd 以及您正在动态创建新列表的事实都看起来很糟糕。你应该在操作节点。
-
@Sanjaya:除非我创建列表,否则我该怎么做?你能再解释一下吗?
标签: c# linked-list