我正在使用 C# 中的通用列表,但是当我尝试使用冒泡排序方法对节点进行排序时出现问题。
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 方法停止工作(无法正确排序列表)。谁能帮我?