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?
You also need to move the
strforward in your loop, else you are continuously adding thesame strin yourlistin every iteration. First element is different for the first time invocation of method. and thenstr.nextis same through out your loop.So, you need to add this code in your for loop: –
Also, your loop has some problem. You should not iterate till the
length(str). But tillstr == null.So, finally your loop should look like this: –
A while loop has to be used in this case, since you don’t know how many times the loop should iterate.