C# 无限循环节点
在显示问题之前,请查看IntNode类:C# 无限循环节点,c#,C#,在显示问题之前,请查看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
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
谢谢 我可以看到关于如何编写冒泡排序的几个问题。如果没有调试器,手动调试将很困难。下面是一个插入排序,它可以为您实现这一技巧,并且更容易在精神上进行跟踪。它查找最低值并将其移动到其他列表
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;
}
这是开始使用调试器的好机会。@zerkms什么是调试器以及我应该如何使用它?这取决于您使用的IDE/编辑器。通过调试编辑你的question@EhsanAkbar我应该修复什么?Tahnks,但我不应该创建一个新列表resultHead和resultTrail。我应该编辑现有的列表。。。我在调试程序中发现了太多的问题,因此如果您能为我编写一个新函数,对给定列表进行排序而不创建新的列表,我将非常高兴