これは宿題です。次の再帰的なディープ コピー メソッドを反復的な同等のメソッドに変更します。私は近づいてきました、そしてそれを正しくするためにあなたの助けが必要です. 再帰的な実装:
public static StringNode copy(StringNode str) {
if (str == null)
return null;
StringNode copyFirst = new StringNode(str.ch, null);
copyFirst.next = copy(str.next);
return copyFirst;
}
これが私が思いついたもので、反復の同等物です。このstatic length()
メソッドは、指定されたリンク リストに含まれるノードの数を返すように既に実装されています。
public static StringNode copy(StringNode str) {
if (str == null)
return null;
StringNode firstNode = new StringNode(str.ch ,null);
StringNode prevNode = firstNode;
StringNode nextNode;
for (int i = 1; i < length(str); i++) {
nextNode = new StringNode(str.next.ch, null);
prevNode.next = nextNode;
prevNode = nextNode;
}
return firstNode;
}
str1
問題: 実装をテストするために、文字値 を含むリンク リストを作成し'n', 'b', 'a'
、 を呼び出します。
StringNode copy = StringNode.copy(str1);
次に、str1 の最後のノードを削除し、そのままにしておきます。'n','b',
ただし、コピーに保存されているコンテンツを印刷しようとすると、
'n', 'b', 'b'
代わりに'n', 'b', 'a'
.
助言がありますか?