我需要編寫一個方法,開始於一個單一的整數鏈表和一個稱爲分裂值的特殊值。列表中的元素沒有特定的順序。該方法將節點分爲兩個鏈接列表:一個包含所有包含小於拆分值的元素的節點和一個包含所有其他節點的節點。如果原始鏈表具有任何重複的整數(即,任何兩個或多個節點中具有相同的元素),則具有此元素的新鏈接列表應具有相同數量的重複該元素的節點。該方法返回兩個頭引用 - 一個用於每個創建的鏈接列表。Java分裂整數鏈接列表
我已經花了無數小時試圖得到這個權利,並認爲這是最接近的,但編譯時我有一個錯誤,我的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;
}
+1不錯的工作;-) – GingerHead