StillLearningToCode
StillLearningToCode

Reputation: 2461

copy a linked list... without using clone

I am trying to write a class method to copy an existing linked list without using clone. my data in the original list is:

3 8 -1 5 12 4 -3 7 0 10 3 6 9 -2 5 11 -6 -4 -2 -1

the issue is that im getting a new list with 20 nodes full of -6. my method is as follows:

public SortedLinkedList copy(){

    SortedLinkedList copy = new SortedLinkedList();

    Node ptr, nodeBefore;

    copy.start = new Node(start.data,null);
    ptr = start.next;
    nodeBefore = copy.start;

    while(ptr != null){
        nodeBefore.next = new Node(start.data, null);
        nodeBefore = nodeBefore.next;
        ptr = ptr.next;
    }
    return copy;

}

Upvotes: 0

Views: 1467

Answers (2)

Noctis
Noctis

Reputation: 11783

That's because you keep creating the nodes with the same start data.

Also, reconsider your variable names. How about calling nodeBefore prevNode?

Another point you could have added is the implementation of your Node class.

Upvotes: 0

Jim Garrison
Jim Garrison

Reputation: 86774

Since this looks like homework, I'll just give you a hint. The problem is in this statement. What data are you putting into the next node?

nodeBefore.next = new Node(start.data, null);

Upvotes: 2

Related Questions