This is an homework assignment. To change the following recursive deep copy method into an iterative equivalent. I came up close, and need your help to make it right. Recursive implementation:
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;
}
Here is what I came up, the iterative equivalent. The static length()
method has been implemented already to return how many nodes are there in a given link list.
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;
}
The problem: to test my implementation, I create a linked list str1
with character value, 'n', 'b', 'a'
, then call
StringNode copy = StringNode.copy(str1);
then I delete the last node of str1, leave it as 'n','b',
however, when i try to print out the content stored in copy, I get
'n', 'b', 'b'
instead of 'n', 'b', 'a'
.
Any suggestions?