我正在C#中使用通用列表,但我尝试使用冒泡排序方法对节点进行排序时遇到问题。在C#中的通用列表Bubblesort#
namespace ConsoleApplication1
{
public class GenericList
{
private class Node
{
// Each node has a reference to the next node in the list.
public Node Next;
public int 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(int t)
{
Node newNode = new Node();
newNode.Next = head;
newNode.Data = t;
head = newNode;
}
//list length
public int Size()
{
int listsize= 0;
Node current = head;
while (current != null)
{
listsize++;
current = current.Next;
}
return listsize;
}
//bubble sort
public void bubblesort()
{
int size = Size();
Node current = head;
for (int i = 1; i < size; i++)
{
for (int j = 0; j < size - 1; j++)
{
if (current.Data > current.Next.Data && current.Next!=null)
{
int temp = current.Data;
current.Data = current.Next.Data;
current.Next.Data = temp;
}
}
}
head = current;
}
}
}
当我向列表添加多于5个节点时,bubblesort方法停止工作(不正确地对列表进行排序)。 任何人都可以帮助吗?
这个功课?如果没有,只需使用List.Sort方法。 – tvanfosson 2011-03-18 16:47:33
确实看起来像一个大学班级的任务与这些意见...呃。 – 2011-03-18 16:49:22
将其称为通用列表会使您听起来像是在使用'System.Collections.Generic.List',而不是您自己定制的'GenericList '。如果这不是家庭作业,只需要删除'GenericList'并使用'List '(或'LinkedList '来更接近地匹配你所拥有的) –
Justin
2011-03-18 16:50:39