Joseph
Joseph

Reputation: 3

What's wrong with this LinkedList result?

I am trying to figure what's wrong with this LinkedList implementation. The result is not what I expected, I thought it should be: 9 4 2 7 5. However, when I run it, only 5 was added. Could someone please explain why? Thanks a lot!

public class LinkedList {

    LinkedList next;
    int value;

    public LinkedList(int value) {
        this.value = value;
        next = null;
    }

    public void add(int n, LinkedList k) {  
        LinkedList node = new LinkedList(n);
        node.next = k;
        k = node;
    }
}


public class LinkedListDemo {

    public static void main(String[] args) {
        LinkedList l = new LinkedList(5);

        l.add(7,l);
        l.add(2,l);
        l.add(4,l);
        l.add(9,l); 

        while(l != null) {
            System.out.println(l.value);
            l = l.next;
        }
    }
}

Upvotes: 0

Views: 107

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

Adding in front would need to change the first node, one solution:

public LinkedList add(int n){
    LinkedList node = new LinkedList(n);

    node.next = this;
    return node;
}

l = l.add(7);

Upvotes: 0

dckrooney
dckrooney

Reputation: 3121

You're losing your changes to k, since Java is passing the reference to k by value. This means that the assignment k = node does not persist when the method exits.

Check out this question for more info on the problem :)

Upvotes: 4

Related Questions