在显示问题之前,请查看IntNode类:
class IntNode
{
public int value { get; set; }
public IntNode next { get; set; }
public IntNode(int value)
{
this.value = value;
this.next = null;
}
public IntNode(int value, IntNode next)
{
this.value = value;
this.next = next;
}
public bool HasNext ()
{
return (this.next != null);
}
public override string ToString()
{
if (this.HasNext())
return this.value + " --> " + this.next;
else
return this.value + ". [end]";
}
}
我有以下功能:
static IntNode Sort (IntNode head)
{
IntNode pos = head.next;
IntNode current = head;
IntNode prev = head;
bool changed = false;
while (current != null)
{
while (pos != null)
{
if (current.value > pos.value)
{
if (pos.HasNext()) current.next = pos.next;
else prev.next = pos;
pos.next = current;
changed = true;
if (current.next.HasNext())
pos = current.next.next;
break;
}
pos = pos.next;
}
if (!changed)
{
current.next = head;
head = current;
}
prev = current;
current = current.next;
changed = false;
}
return head;
}
但是当我启动程序时(使用给定的参数)它没有响应(" - "出现并消失)我不知道为什么会这样,我坐在这一小时...
程序的目的是列表并从小到大排序,然后返回编辑的列表(不要创建另一个列表)。
例如:
给定列表:
6,-4,5,0
输出:
-4,0,5,6
谢谢!
答案 0 :(得分:0)
我可以看到有关如何编写冒泡排序的几个问题。如果您没有调试器,则很难手动调试。这是一个插入排序,可以为您提供技巧,更容易在心理上进行跟踪。它找到最低值并将其移动到不同的列表。
static IntNode Sort (IntNode head)
{
IntNode resultTail = null;
IntNode resultHead = null;
IntNode current = head;
IntNode lowestPrev = null;
IntNode lowest = head;
while (head != null)
{
lowestPrev = null;
current = head;
while (current != null)
{
if (current.value < lowest.value)
{
lowest = current;
lowestPrev = prev;
}
prev = current
current = current.next;
}
if (resultHead = null)
{
resultHead = lowest;
resultTail = lowest;
}
else
resultTail.next = lowest;
if (lowest == head)
head = head.next;
else
lowestPrev.next = lowest.next;
}
return resultHead;
}