我需要编写一个以单个整数链表和一个称为拆分值的特殊值开头的方法。列表的元素没有特定的顺序。该方法将节点划分为两个链表:一个包含包含小于拆分值的元素的所有节点,另一个包含所有其他节点。如果原始链表有任何重复的整数(即任何两个或多个具有相同元素的节点),则具有该元素的新链表应该具有相同数量的重复该元素的节点。该方法返回两个头引用——一个用于创建的每个链接列表。
我已经花费了无数个小时试图做到这一点,并认为这是最接近的,但在编译时出现错误,我的 copyTail* IntNodes 可能未初始化。我的代码也可能完全错误....有任何帮助指向我正确的方向吗?
public static IntNode[ ] listSplitLessGreater(IntNode source, int splitter)
{
IntNode copyHeadLess;
IntNode copyTailLess;
IntNode copyHeadGreater;
IntNode copyTailGreater;
IntNode[ ] answer = new IntNode[2];
boolean less = true;
boolean greater = true;
// Handle the special case of the empty list.
if (source == null)
return answer; // The answer has two null references .
//Split list into two lists less and greater/equal than splitter.
while (source.link != null)
{
if (splitter < source.data)
{
if (less)
{
copyHeadLess = new IntNode(source.data, null);
copyTailLess = copyHeadLess;
less=false;
}
else
{
source = source.link;
copyTailLess.addNodeAfter(source.data);
copyTailLess = copyTailLess.link;
}
}
else
{
if (greater)
{
copyHeadGreater = new IntNode(source.data, null);
copyTailGreater = copyHeadGreater;
greater=false;
}
else
{
source = source.link;
copyTailGreater.addNodeAfter(source.data);
copyTailGreater = copyTailGreater.link;
}
}
}
//Return Head References
answer[0] = copyHeadLess;
answer[1] = copyHeadGreater;
return answer;
}