Hank
Hank

Reputation: 199

iteratively deep copy a link list

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?

Upvotes: 4

Views: 17361

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213351

You also need to move the str forward in your loop, else you are continuously adding the same str in your list in every iteration. First element is different for the first time invocation of method. and then str.next is same through out your loop.

So, you need to add this code in your for loop: -

str = str.next;

Also, your loop has some problem. You should not iterate till the length(str). But till str == null.

So, finally your loop should look like this: -

while (str.next != null) {  // Iterate till str.next != null, as we are creating 
                            // the next node in the loop for current node str

    nextNode = new StringNode(str.next.ch, null);
    prevNode.next = nextNode;
    prevNode = nextNode;

    str = str.next;  // Move to next node.
}

A while loop has to be used in this case, since you don't know how many times the loop should iterate.

Upvotes: 5

Related Questions