Java の割り当てに関するアドバイスを探しています。私が求められているのは、リンクされたリストに格納されている数値に対してさまざまな操作を実行し、各桁を個別のノードに配置することです。ポイントは、非常に大きな数の算術演算を実行できるプログラムを作成することです。
私が助けを求めている特定の問題は、int の通常の compareTo() メソッドと同様に、2 つの数値を比較するメソッドを作成することです。this.num < num の場合は -1、this.num > num の場合は +1、等しい場合は 0 を返します。
私にとってこれを困難にしているのは、割り当てが、リンクされたリストが逆の順序で番号を格納する必要があることを指定しているという事実です。たとえば、番号 145 のリンク リストは次のようになります。
5 => 4 => 1 => null
これにより、数値を簡単に追加できますが、比較しようとすると頭痛の種になります。これが私が思いついたものです。コメントは、それがどのように機能するかを説明しています。
public int compareTo(LLNum list)
{ // Compares two numbers.
// If the two numbers are of a different length, clearly the shortest is the smallest.
// If the two numbers are of equal length, call traverseToCompare to do the comparison.
if (this.len > list.len)
{
compareResult = 1;
}
else if (this.len < list.len)
{
compareResult = -1;
}
else if (this.len == list.len)
{
traverseToCompare(this.head, list.head);
}
return compareResult;
}
public void traverseToCompare(ListNode node1, ListNode node2)
{ // In the case that both numbers are of the same length, recursively traverse the list.
// compare each digit individually while unwinding the stack.
// Once two digits are found to be different, break out of the unwinding (Note: I could not find a way of breaking out)
// Since the dominant digit is at the tail end, this ensures the least number of comparisons.
if (node1 == null || node2 == null)
{ // Base case. Handles the case where both numbers are identical.
compareResult = 0;
return;
}
traverseToCompare(node1.getNext(), node2.getNext());
if (node1.getItem() > node2.getItem())
{
compareResult = 1;
}
if (node1.getItem() < node2.getItem())
{
compareResult = -1;
}
return;
}
数字が逆順になっていることが、私を再帰に引き寄せた理由です。リストを再帰的にトラバースし、途中で各桁を比較し、最初の桁が同じではない再帰から何らかの方法で抜け出すと思いました。これは再帰を使用する通常の方法ではないことはわかっていますが、他に方法がわかりませんでした。例外をスローするだけで壊れる方法はありますか? それは少しずさんすぎるかもしれないと思います。または、再帰なしでこれを行う方法に関する提案はありますか?
コピーして貼り付けるコードを教えてください。私はただ正しい方向に向けられることを望んでいます。ありがとう!